How to update table with while loop in Stored Procedure? - sql

I want to update my dynamic table in while loop.
Here is my code:
While (#j<=#tmp_getRowCount)
Begin
Set #firstcolumn = (Select SplitFirst_tblAR from #result_AR Where rownumber = #j) //String//
Set #secondcolumn = (Select EMail_tblAR from #result_AR Where rownumber = #j) //String//
Set #thirdcolumn = (Select SplitFirst_tblKul from #result_AR Where rownumber = #j) //String//
Set #fourthcolumn = (Select EMail_tblKul from #result_AR Where rownumber = #j) //String//
insert into #test Values(#tmp_ID, #firstcolumn,#secondcolumn,#thirdcolumn,#fourthcolumn)
if ((#firstcolumn = #thirdcolumn) AND (#secondcolumn != #fourthcolumn) AND (#firstcolumn != ''))
begin
Set #q_updateTable = 'Update '+ quotename(#tablename) +' Set '+#columnname+' = ''' + #fourthcolumn + ''' Where ID = ' + #tmp_ID + ''
Exec sp_executesql #q_updateTable
end
SET #j = #j+1
End
My result_AR table:
I know the error is in here:
Where ID = ' + #tmp_ID + ''
When I change this Where clause as,
Where '+#columnname+' = ''' + #secondcolumn + ''' '
code works correctly.
Why can't I set as ID my where clause? I am getting ID value as integer.
The error is 'Query completed with errors'.
Thanks in advance.

you can not set Id in where clause because the id is integer value and you are concatenating it with string (varchar).
So first you have to convert it in (String)varchar and the you can use it where clause.
Like :
Set #q_updateTable = 'Update '+ quotename(#tablename) +' Set '+#columnname+' = ''' + #fourthcolumn + ''' Where ID = ' + convert(varchar,#tmp_ID) + ''
Exec sp_executesql #q_updateTable
you have to use "convert(varchar,#tmp_ID)" insted of "#tmp_ID"

Related

SQL - Dynamic Condition in Where Clause

I have the following stored proc. The issue I'm having is with the "conditions" parameter. Basically each condition is its own column so it it passed in like this-
#Conditions = ' AND hcc_108 = 1 AND ...' etc.
I'm trying to do something like this-
ALTER PROC [dbo].[GetPatientPanelList]
(
#CareProviderId int=null,
#Patient nvarchar(60)=null,
#Conditions varchar=null,
#LocationId int=null
)
AS
if #Conditions is null
SELECT *
FROM vw_patient_attributes t1
INNER JOIN STG_OSHODS_DW.osh_rpt.dim_member_care_measures t2
ON t1.PatientID = t2.emr_id
WHERE
(t1.PreferredServiceLocationID = #LocationId OR #LocationId IS NULL)
AND (t1.CareProviderID = #CareProviderId OR #CareProviderId IS NULL)
AND (t1.FullName like '%' + #Patient + '%' OR #Patient IS NULL)
else
SELECT *
FROM vw_patient_attributes t1
INNER JOIN STG_OSHODS_DW.osh_rpt.dim_member_care_measures t2
ON t1.PatientID = t2.emr_id
WHERE
(t1.PreferredServiceLocationID = #LocationId OR #LocationId IS NULL)
AND (t1.CareProviderID = #CareProviderId OR #CareProviderId IS NULL)
AND (t1.FullName like '%' + #Patient + '%' OR #Patient IS NULL)
+ #Conditions
I just need the last AND condition to populate based off the parameter. I understand that the " + " is the syntax error but I can't seem to figure out a way on how to implement this.
Thanks!
Update
I have tried dynamic sql but it keeps saying "Command(s) completed successfully)"
Here is my current code. I wrote this in a separate window to first get the query to work.
DECLARE #where nvarchar(50) = ' and hcc_18 = 1'
,#sql nvarchar(MAX) ,
#CareProviderId int=null,
#Patient nvarchar(60)=null,
#LocationId int=null
set #sql = 'select *
FROM vw_patient_attributes t1
INNER JOIN STG_OSHODS_DW.osh_rpt.dim_member_care_measures t2
ON t1.PatientID = t2.emr_id
WHERE t1.PreferredServiceLocationID = IsNull('+ convert(varchar,#LocationId) +',t1.PreferredServiceLocationID)
AND (t1.CareProviderID = isnull(' + convert(varchar,#CareProviderId)+ ', t1.CareProviderID)
AND (t1.FullName like %' + #Patient + '% OR ' + #Patient + ' IS NULL)' + #where
exec(#sql)
I fixed the syntax issues in your last updated. This should work...
DECLARE #where nvarchar(50) = ' and hcc_18 = 1'
,#sql nvarchar(MAX) ,
#CareProviderId int=null,
#Patient nvarchar(60)=null,
#LocationId int=null
set #sql = 'select *
FROM vw_patient_attributes t1
INNER JOIN STG_OSHODS_DW.osh_rpt.dim_member_care_measures t2
ON t1.PatientID = t2.emr_id
WHERE t1.PreferredServiceLocationID = case when '+ convert(varchar(8),isnull(#LocationId,0)) +' = 0 then t1.PreferredServiceLocationID else ' + convert(varchar,isnull(#LocationId,0)) + ' end
AND (t1.CareProviderID = case when ' + convert(varchar,isnull(#CareProviderId,0)) + ' = 0 then t1.CareProviderID else ' + convert(varchar,isnull(#CareProviderId,0)) + ' end
AND (t1.FullName like ''%' + isnull(#Patient,'') + '%'' OR ' + isnull(#Patient,0) + '=0)' + #where
print(#sql)
--exec(#sql)
Check my answer at
No need to use ad-hoc query (just execute SP_ExecuteSQL)
Check below logic, you can use N number of dynamic / un-sure parameters / conditions........

SQL Server: Error message on dynamic procecure

I don't have much experience with dynamic procedures so the following was only an attempt.
The only part that is actually dynamic here is the table name which I tried to create by combining the fix part "MOC_" and the variable part #level.
Can someone tell me what I have to change here to make this work ?
The error I get when executing this points to the IF NOT EXISTS part:
Conversion failed when converting the nvarchar value 'IF NOT EXISTS (
SELECT *
FROM MOC_Nav2
WHERE itemID = ' to data type int.
My procedure:
ALTER PROCEDURE [dbo].[MOC_UpdateNav]
#level nvarchar(20),
#itemID int,
#parentID int,
#itemName nvarchar(100),
#sortID int,
#logStatus nvarchar(20),
#lastUpdate nvarchar(50),
#modBy varchar(50)
AS
BEGIN
SET NOCOUNT ON;
BEGIN
DECLARE #sql nvarchar(max)
SET #sql = 'IF NOT EXISTS
(
SELECT *
FROM MOC_' + #level + '
WHERE itemID = ' + #itemID + '
)
INSERT INTO MOC_' + #level + '
(
parentID,
itemName,
sortID,
logStatus,
lastUpdate,
modDate,
modBy
)
SELECT ' + #parentID + ',
' + #itemName + ',
' + #sortID + ',
' + #logStatus + ',
' + #lastUpdate + ',
GETDATE(),
' + #modBy + '
ELSE
UPDATE MOC_' + #level + '
SET parentID = ' + #parentID + ',
itemName = ' + #itemName + ',
sortID = ' + #sortID + ',
logStatus = ' + #logStatus + ',
lastUpdate = ' + #lastUpdate + ',
modDate = GETDATE(),
modBy = ' + #modBy + '
WHERE itemID = ' + #itemID + ''
EXEC(#sql)
END
END
#itemID is an int. Because it is used in the expression, everything else must be converted to a number, including your SQL text.
Convert #itemID (and other numbers) to nvarchar before concatenating it into the query:
SET #sql = N'IF NOT EXISTS
(
SELECT *
FROM MOC_' + #level + '
WHERE itemID = ' + cast(#itemID as nvarchar(30)) + ...

Dynamic sql stored procedure update query issue?

I've written the below code to set filepath column in my table as 'F:\DataMigration\Wise\DELTA_20121008\Attachments\SR\SR_1.txt'
where SR_1 is file_name column
.txt is file_ext column from my table.
but after executing following procedure, I'm getting filepath column in table as
'F:\DataMigration\Wise\DELTA_20121008\Attachments\file_name.file_ext'
means It's treating column names as string, how i can make it as column so it will
use values in that column.
alter procedure [dbo].[WISEMissingAttachmentReportGenerator]
(
#tablename varchar(255), #pathonlocal nvarchar(255)
)
as
begin
--step 1
exec dbo.proc_alter_table #tablename
--step 2
EXEC ('update '+ #tablename +
' set filepath = '''+ #pathonlocal + ' file_name'+'.'+'file_ext''')
EXEC('Select * from '+#tablename)
end
exec [dbo].[WISEMissingAttachmentReportGenerator] [WISE.Non_VP_Service_Request_Attachments_File_Check_Analysis],
N'F:\DataMigration\Wise\DELTA_20121008\Attachments\SR\'
Try;
EXEC('UPDATE '+ #tablename +
' SET filepath = '''+ #pathonlocal + ''' + file_name + '''+'.'+''' + file_ext')
Equal as;
UPDATE [YourTable] SET filepath = 'YourPath' + file_name + '.' + file_ext
Try changing your statement to this:
EXEC ('update '+ #tablename +
' set filepath = '''+ #pathonlocal + ''' + file_name + ''.'' + file_ext')
declare #tblnm varchar(20) = 'test'
declare #upda varchar(20) = 'update '
declare #set varchar(25) = ' set'
declare #id varchar(25) = ' id'
declare #cmd varchar(1000)
set #cmd = #upda + #tblnm + #set + #id + '=7'
exec(#cmd)
SAMPLE SQL UPDATE QUERY - FOR BUILDING TABLENAME DYNAMICALLY
EXECUTED GUYS - THIS IS CALL JUGAAAAAAAAAD [NO NEED TO GET INTO ''' STUFF]

How to copy, replace, and insert across all rows in the database

I'll do my best to explain:
Copy all rows that exist in current database
Mass replace a specific string value in every row that contains a specific field
Insert the copied rows
Not sure what approach to take other than hammering out sql scripts.
Thanks!
Is this as simple as creating an Data Flow Source, selecting all the rows, then passing them to a Derived Column transformation, which would be along the lines of:
REPLACE( [ColumnName], "SpecificValue", "ReplacementValue" )
and then insert these rows into your destination table using the relevant Data Flow Destination.
I may be misunderstanding or simplifying step 2...
Assuming you have a table called "table2" and that table consists of the columns facilabbr, unitname, and sortnum... You can select all rows into a temporary table (# signifies a temporary table) changing the "unitname" column to something else...You'll be left with the new values in the temporary table. You can then replace the values in your initial table if you want.
INSERT INTO #temptable1
SELECT facilabbr,
'myNewUnitName' as unitname,
sortnum
FROM table2
DELETE FROM table2
INSERT INTO table2
SELECT facilabbr,
unitname,
sortnum
FROM #temptable1
--THIS QUERY IS ONLY EQUIPPED TO HANDLE:
--SIMPLE NUMERICS SUCH AS FLOATS, INTS, ETC
--SIMPLE STRING DATA TYPES LIMITED TO: VARCHARS, CHARS, NCHARS AND NVARCHARS
--DATES AND DATETIMES
Create Procedure SQLCloner
#TableName as VarChar(max), -- Table that holds data to clone.
#NewTableName as VarChar(max) = '', -- Table to Insert into. If same as Tablename leave blank or write ''.
#VarCharFind as VarChar(max) = '', -- Value to find (In order to replace). If you aren't replacing leave blank or write ''.
#VarCharReplace as VarChar(max) = '', -- Value to replace. If you aren't replacing leave blank or write ''.
#OptionalParam As VarChar(Max) = '' -- Your WHERE clause. If you have none leave blank or write ''.
AS
Declare #index as int = 1
Declare #rowcount As Int = 0
Declare #execFunction As VarChar(max) = ''
Declare #InsertTableRowName As VarChar(max) = ''
Declare #TempFilterType As VarChar(Max) = ''
--Create RowCount of Table
Select #ROWCOUNT = Count(*)
From (
Select Column_Name
From INFORMATION_SCHEMA.COLUMNS
Where Table_Name = '' + #TableName + ''
) As TheCount
--Use While Loop to create Table Columns
While #index <= #rowcount
Begin
--Determines the Variable type to change the exec function accordingly
Select #TempFilterType = TypeTable.DATA_TYPE
From (
Select Data_Type,
ROW_NUMBER() OVER (Order By Ordinal_Position) as RowNum
From INFORMATION_SCHEMA.COLUMNS
Where Table_Name = #TableName
) As TypeTable
Where TypeTable.RowNum = #index
--Prepares #InsertTableRowName With the first part of the string
Set #InsertTableRowName = Case
When #TempFilterType IN('varchar', 'nvarchar','char', 'nchar')
Then #InsertTableRowName + ''''''''' + '
When #TempFilterType IN('datetime', 'date')
Then #InsertTableRowName + ''''''''' + Convert(varchar(Max), '
Else
#InsertTableRowName + 'Convert(varchar(Max), '
End
--Determines the Name of the Column
Select #InsertTableRowName = #InsertTableRowName +
Case
When #TempFilterType IN('varchar', 'nvarchar','char', 'nchar')
Then 'ISNULL(' + 'Replace(' + Column_Name + ','''''''','''''''''''')' + ','''')'
When #TempFilterType IN('datetime', 'date')
Then 'ISNULL(' + 'Replace(' + Column_Name + ','''''''','''''''''''')' + ',''12/31/9999'')'
Else
'ISNULL(' + 'Replace(' + Column_Name + ','''''''','''''''''''')' + ',0)'
End
From (
Select Column_Name,
ROW_NUMBER() OVER (Order By Ordinal_Position) As RowNum
From INFORMATION_SCHEMA.COLUMNS
Where Table_Name = #TableName
) As TheRow
Where RowNum = #index
--Finishes Closes each column insert (in every instance)
Set #InsertTableRowName = Case
When #TempFilterType IN('varchar', 'nvarchar','char', 'nchar')
Then #InsertTableRowName + ' + '''''''''
When #TempFilterType IN('datetime', 'date')
Then #InsertTableRowName + ') + '''''''''
Else
#InsertTableRowName + ') '
End
--Links each Row together with commas and plus signs until the very end.
If #index < #rowcount
Begin
Set #InsertTableRowName = Case
When #TempFilterType IN('varchar', 'nvarchar','char', 'nchar')
Then #InsertTableRowName + ' + ' + ''',''' + ' + '
When #TempFilterType IN('datetime', 'date')
Then #InsertTableRowName + ' + '','' + '
Else
#InsertTableRowName + ' + '','' + '
End
End
Set #index = #index + 1
End
--Puts the Query together (without any of the Parameters yet).
--First, determine if a new table should be used instead.
If #NewTableName = ''
Begin
Set #NewTableName = #TableName
End
--Next, Build the Query, and do it accordingly with if there is a Find/Replace asked for.
Set #execFunction = 'Select '
If #VarCharFind <> ''
Begin
Set #execFunction = #execFunction + 'Replace('
End
Set #execFunction = #execFunction + '''insert into ' + #NewTableName + ' Values('' + ' + #InsertTableRowName + ' + '')'' '
If #VarCharFind <> ''
Begin
Set #execFunction = #execFunction + ', ''' + #VarCharFind + ''', ''' + #VarCharReplace + ''') '
End
Set #execFunction = #execFunction + 'From ' + #TableName
--Adds in the optional Parameters
If #OptionalParam <> ''
Begin
Set #execFunction = #execFunction + ' ' + #OptionalParam
End
Set #execFunction = #execFunction + CHAR(13)+CHAR(10)
--Executes the function and pulls an entire set of queries to copy into the new Database
Print #execFunction
Exec(#execFunction)
GO

SQL Query within VS TableAdapter Query Configuration Wizard

I am trying to write an SQL query within Visual Studio TableAdapter Query Wizard
My SQL query is:
DECLARE #SQL varchar(255);
SET #SQL = ' SELECT * FROM dbAddress WHERE 1 = 1'
IF #ApexLine1 = ''
BEGIN
SET #SQL = #SQL + ' AND addLine1 IS NULL '
END
ELSE
BEGIN
SET #SQL = #SQL + ' AND addLine1 = ''' + #ApexLine1 + ''''
END
IF #ApexLine2 = ''
BEGIN
SET #SQL = #SQL + ' AND addLine2 IS NULL '
END
ELSE
BEGIN
SET #SQL = #SQL + ' AND addLine2 = ''' + #ApexLine2 + ''''
END
IF #ApexLine3 = ''
BEGIN
SET #SQL = #SQL + ' AND addLine3 IS NULL '
END
ELSE
BEGIN
SET #SQL = #SQL + ' AND addLine3 = ''' + #ApexLine3 + ''''
END
IF #ApexZip = ''
BEGIN
SET #SQL = #SQL + ' AND addPostCode IS NULL '
END
ELSE
BEGIN
SET #SQL = #SQL + ' AND addPostCode = ''' + #ApexZip + ''''
END
IF #ApexCity = ''
BEGIN
SET #SQL = #SQL + ' AND addLine4 IS NULL '
END
ELSE
BEGIN
SET #SQL = #SQL + ' AND addLine4 = ''' + #ApexCity + ''''
END
IF #ApexProv = ''
BEGIN
SET #SQL = #SQL + ' AND addLine5 IS NULL '
END
ELSE
BEGIN
SET #SQL = #SQL + ' AND addLine5 = ''' + #ApexProv + ''''
END
EXEC(#SQL)
I get the error:
'The Declare SQL contruct or statement is not supported'
If I remove the Declare statement I get error:
'The Set SQL construct or statement is not supported'
Is there a work around for this?
Thanks.
Anything like this:
SET #SQL = #SQL + ' AND addLine1 = ''' + #ApexLine1 + ''''
is EVIL. Don't do it. Variables like #ApexLine1 could contain anything, even something like this:
';DROP TABLE dbAddress--
Think very carefully about what would happen if someone entered something like that in your Address Line 1 field. The only correct solution here is to use the built-in sp_executesql stored procedure. Learn it, use it.
Aside from that, I think at least part of your problem might be that your #SQL variable is only 255 characters. It's easily possible your query is running out of space.