I need to modify a stored procedure that will update a price table on a live database.
I am using MS SQL Server 2005, and the stored procedure is used as a query in SAP BI.
I have this part:
SET #cmd ='Update PriceList 5'
SET #sql ='UPDATE a SET a.price= round( (b.price*0.9),0), a.currency=b.currency FROM ['+#trgDB+'].[dbo].[ITM1] a '
SET #sql =#sql+' INNER JOIN ['+#trgDB+'].[dbo].[ITM1] b ON ( a.ItemCode=b.itemcode AND b.PriceList=1) '
SET #sql =#sql+' WHERE a.PriceList=5 '
IF #filter IS NOT NULL BEGIN
SET #sql =#sql+' AND a.[ItemCode] LIKE '+char(39)+#filter+'%'+char(39)+' '
SET #cmd = #cmd+' ('+#filter+'%'+') '
END
This will update the price on every item acording to filter.
I need to leave some items unchanged, so how can I add NOT LIKE 'VSK%' AND NOT LIKE 'VFH%' to the code above? It doesn't matter if the flter is left out, but then I need every price to be updated except NOT LIKE 'VSK%' AND NOT LIKE 'VFH%' .
table http://qupload.com/images/clipbosjs.jpg
Related
I want to create RDLC report ,but the problem is that Columns in a table returned by the stored procedure are Dynamic, means Columns can be increased or decrease depends on the condition.
I have Created procedure.
alter proc sp_GetEmpBranAndDesigWise(
#BranchId nvarchar(200),
#ZoneId nvarchar(200)
)
as
if 1=0 Begin
set FMTONLY OFF End
select b.BranchName,b.BranchCity,z.ZoneName,b.BranchID,d.DesigName
,Count(d.DesigName) as TotalCount
INTO #RepTablTemp
from Emp_File emp
INNER join Branch b on emp.BranchID=b.BranchID
left join ZoneFile z on z.ZoneID=b.ZoneID
INNER join SWHouse_Production.dbo.emp_DesigFile d on emp.DesigID=d.DesigID
where Convert(nvarchar(250), b.BranchID) like #BranchId
and Convert(nvarchar(250), b.ZoneID) like #ZoneId
group by b.BranchName,z.ZoneName,b.BranchCity,b.BranchID,d.DesigName
order by b.BranchName,z.ZoneName,d.DesigName
--select * from #RepTablTemp order by BranchName,DesigName
--select * from Emp_File where BranchID=1055
Begin
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT DISTINCT ',' + QUOTENAME(DesigName)
from #RepTablTemp
group by DesigName
--order by 1
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
print #cols
set #query = N'SELECT BranchName,ZoneName,BranchCity,' + ISNULL(#cols,'0') + N' from
(
select BranchName,ZoneName,BranchCity,TotalCount, DesigName
from #RepTablTemp
) x
pivot
(
max(TotalCount)
for DesigName in (' + #cols + N')
) p '
exec sp_executesql #query;
select 0 AS mycol1int
print #query
drop table #RepTablTemp
End
BranchName|ZoneName|BranchCity|Designation1|Designation2|Designation3
here Designations are dynamic and can be increased,i want this kind of result in RDLC
enter image description here
In attached file highlighted fields are Designations coming from Designation Table.
You can't do that. RDLC expects a fixed "object" for a table. You can pass a dynamic object, but this object must be match with the dataset provided to the table.
But you can use several tablix and show them or not (visibility condition) for an specific condition loaded by a parameter (for example, a kind of table do you want to see or hide).
I need a stored procedure with dynamic select statement, in my case only adding desired column names in select. This is what I created, but I'm not sure If It's safe for SQL injections:
CREATE OR REPLACE PROCEDURE MySchema.Search(
columns IN VARCHAR2,
res_out OUT SYS_REFCURSOR)
IS
BEGIN
OPEN res_out FOR
'SELECT ' || columns ||' FROM MySchema.Table1';
END Search;
Is this fine or is It not safe ? When reading all examples I haven't noticed anything easy as this, but It works. If It's not safe for SQL injections, please show me how I should do It. Thanks for help in advance !
I will suggest to you use your PL/SQL like this: in the below PL/SQL it ensures that, if any of the SQL Injection statement is trying to invoke it will stop.
CREATE OR REPLACE PROCEDURE MySchema.Search(
columns IN VARCHAR2,
res_out OUT SYS_REFCURSOR)
IS
v_columns VARCHAR2(4000);
BEGIN
select listagg(column_name,',') within group(order by 1)
INTO v_columns
from all_tab_columns
where owner = 'MYSCHEMA'
and table_name = 'TABLE1'
and column_name in (select regexp_substr(columns,'[^,]+', 1, level)
from dual
connect by regexp_substr(columns, '[^,]+', 1, level) is not null
);
OPEN res_out FOR
'SELECT ' || v_columns ||' FROM MySchema.Table1';
END Search;
I have a stored procedure in Informix that uses external tables to unload data to a disk file from a select statement. Is it possible to give the DISK file name as a parameter to the stored procedure? My stored procedure is as follows:
create procedure spUnloadData(file_name_param varchar(64))
create temp table temp_1(
col_11 smallint
) with no log;
INSERT INTO temp_1 select col1 from data_table;
CREATE EXTERNAL TABLE temp1_ext
SAMEAS temp_1
USING (
--DATAFILES ("DISK:/home/informix/temp.dat")
DATAFILES("DISK:" || file_name_param )
);
INSERT INTO temp1_ext SELECT * FROM temp_1;
DROP TABLE temp1_ext ;
DROP TABLE temp_1;
END PROCEDURE;
I am trying to pass in the DISK filename as a parameter(from my shell script, timestamped).
Any help is appreciated.
NH
You would have to use Dynamic SQL in the stored procedure — for example, the EXECUTE IMMEDIATE statement.
You create a string containing the text of the SQL and then execute it. Adapting your code:
CREATE PROCEDURE spUnloadData(file_name_param VARCHAR(64))
DEFINE stmt VARCHAR(255); -- LVARCHAR might be safer
CREATE TEMP TABLE temp_1(
col_11 SMALLINT
) WITH NO LOG;
INSERT INTO temp_1 select col1 from data_table;
LET stmt = 'CREATE EXTERNAL TABLE temp1_ext ' ||
'SAMEAS temp_1 USING DATAFILES("DISK:' ||
TRIM(file_name_param) ||
'")';
EXECUTE IMMEDIATE stmt;
INSERT INTO temp1_ext SELECT * FROM temp_1;
DROP TABLE temp1_ext;
DROP TABLE temp_1;
END PROCEDURE;
Untested code — the concept should be sound, though.
This assumes you are using a reasonably current version of Informix; the necessary feature is in 12.10, and some version 11.70 versions too, I believe.
I made slight changes to my code to unload data(as Informix default '|' separated fields). Instead of using a temp table, I was able to select columns directly into an external table dynamically.
Is is possible to create a stored procedure using cfstoredproc? When I run the following I get Incorrect syntax near 'GO'.
<cffile action="read" file="mypath/myFile.sql" variable="sp_1">
<cfstoredproc procedure="sp_executesql" dataSource="#getDatasource()#">
<cfprocparam type="in" cfsqltype = "cf_sql_varchar" value ='#sp_1#'>
</cfstoredproc>
myFile.sql
IF OBJECT_ID('getMyData', 'P') IS NOT NULL
DROP PROC getMyData
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE getMyData
#some_var AS NVARCHAR(200)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #sql AS NVARCHAR(MAX)
SET #sql = N'SELECT * FROM myTable where id = ''' + #some_var + ''' '
EXEC sp_executeSQL #sql
END
<cfquery name="createGetMyData" dataSource="#getDatasource()#">
#preservesinglequotes(sp_1)#
</cfquery>
Try this:
<cffile action="read" file="mypath/myFile.sql" variable="sp_1">
<cfstoredproc procedure="sp_executesql" dataSource="#getDatasource()#">
<cfprocparam type="in" cfsqltype = "cf_sql_varchar" value ='#preservesinglequotes(sp_1)#'>
</cfstoredproc>
ColdFusion escapes your single quotes in db variables.
EDIT:
Secondly there is the batching of statements. the drive will batch your query as a single statement wheras the "GO" keyword is an indicator of a batch prepared. In other words, your "GO" actually IS the issue.
To fix it you will need to run 2 querys - one to drop and the other to create. Why? Because CREATE PROCEDURE actually has to be the first statement in a given batch. in MSSQL studio, using GO, you are creating 3 batches, now you have to figure out how to use one.
The good news is that your ANSI nulls and Quoted identifiers are probably not needed - they are defaulted on most instances.
Does this help?
I am trying to write a stored procedure to match lists of physicians with existing records in our database based off of the information provided to us by our clients. Currently we use MS Access to join manually based on the given identifiers, but this process tends to be tedious and overly time consuming, hence the desire to automate it.
What I am trying to do is create a temporary table that contains all columns that could potentially be matched on, and then run through a series of matching queries using the fields as join conditions to get our identifier to pass back.
For instance, the available matching fields are Name, NPI, MedicaidNum, and DOB so I would write something like:
UPDATE Temp
SET Temp.RECID = Phy.RECID
FROM TempTable Temp
INNER JOIN Physicians Phy
ON Phy.Name = Temp.Name
AND Phy.NPI = Temp.NPI
AND Phy.MedicaidNum = Temp.MedicaidNum
AND Phy.DOB = Temp.DOB
UPDATE Temp
SET Temp.RECID = Phy.RECID
FROM TempTable Temp
INNER JOIN Physicians Phy
ON Phy.Name = Temp.Name
AND Phy.NPI = Temp.NPI
AND Phy.MedicaidNum = Temp.MedicaidNum
WHERE Temp.RECID IS NULL
...etc
The problem lies in the fact that there about 15 different identifiers which could potentially be provided and clients usually only provide three or four per record set. So by the time null values are accounted for, there are potentially over a hundred different queries that need to be written to match on only half a dozen provided fields.
I am thinking that there may be a way to pass in a variable (or variables) which indicate which columns are actually provided with the data set, and then write a dynamic join statement and/or where clause, but I do not know if this will work in T-SQL. Something like:
DECLARE #Field1
DECLARE #Field2
....
UPDATE Temp
SET Temp.RECID = Phy.RECID
FROM TempTable Temp
INNER JOIN Physicians Phy
ON Phy.#Field1 = Temp.#Field1
AND Phy.#Field2 = Temp.#Field2
This way I would limit the number of queries I need to write, and only need to worry about the number of fields I am matching, rather then which specific ones. Perhaps there is a better approach to this problem however?
You can do something like this, but be warned this method is super prone to SQL injection. It's just to illustrate the principle of how to do something like this. I leave it up to you what you want to do with it. For this code, I made the proc take three fields:
CREATE PROC DynamicUpdateSQLFromFieldList #Field1 VARCHAR(50) = NULL,
#Field2 VARCHAR(50) = NULL,
#Field3 VARCHAR(50) = NULL,
#RunMe BIT = 0
AS
BEGIN
DECLARE #SQL AS VARCHAR(1000);
SELECT #SQL = 'UPDATE Temp
SET Temp.RECID = Phy.RECID
FROM TempTable Temp
INNER JOIN Physicians Phy ON ' +
COALESCE('Phy.' + #Field1 + ' = Temp.' + #Field1 + ' AND ', '') +
COALESCE('Phy.' + #Field2 + ' = Temp.' + #Field2 + ' AND ', '') +
COALESCE('Phy.' + #Field3 + ' = Temp.' + #Field3, '') + ';';
IF #RunMe = 0
SELECT #SQL AS SQL;
ELSE
EXEC(#SQL)
END
I've added a debug mode flag just so you can see the SQL if you don't want to run it. So, for example, if you run:
EXEC DynamicUpdateSQLFromFieldList #field1='col1', #field2='col2', #field3='col3'
or
EXEC DynamicUpdateSQLFromFieldList #field1='col1', #field2='col2', #field3='col3', #RunMe=0
the SQL produced will be:
UPDATE Temp
SET Temp.RECID = Phy.RECID
FROM TempTable Temp INNER JOIN Physicians Phy
ON Phy.col1 = Temp.col1 AND
Phy.col2 = Temp.col2 AND
Phy.col3 = Temp.col3;
If you run this line:
EXEC DynamicUpdateSQLFromFieldList #field1='col1', #field2='col2', #field3='col3', #RunMe=1
It will perform the update. If you wanted it to be more secure, you could whitelist the incoming field names against the sys tables to make sure the columns actually exist in each table before you execute any code.