Error in using SELECT to set a variable value in SQL - sql

I have following stored procedure and I have identified the issue with the stored procedure is that using select to set the value of #DeliveryAddress variable and so for all the Letter Requests raised it is only retaining the last value which is in Requests. I tried using SET by explicitly setting each value used in #DeliveryAddresss Calculation but of no use as I ended of getting error that subquery returns multiple rows.
I am unable to understand what shall I change in this SP, so that for each value in #Requests, a different #deliveryAddress value is set and used for insertion in LetterRequest table. Please help.
Note #WorkFlowAcct is a temp table having around 10 unique AccountIds and for each account we have atleast one debtorid.
ALTER PROCEDURE [dbo].[WorkFlow_Action_RequestLetterPref]
AS
DECLARE #LetterID INTEGER;
DECLARE #LetterType CHAR(3);
DECLARE #LetterDescription VARCHAR(50);
DECLARE #JobName VARCHAR(256);
DECLARE #DateCreated DATETIME;
DECLARE #DeliveryMethod VARCHAR(7);
DECLARE #DeliveryAddress VARCHAR(1023);
SELECT #LetterID = [LetterID],
#LetterType = CASE
WHEN [type] IN ('SIF', 'PIF', 'PPS', 'PDC', 'ATT', 'CUS') THEN [type]
ELSE 'DUN'
END,
#LetterDescription = ISNULL([Description], ''),
FROM [dbo].[letter]
WHERE [code] = #LetterCode;
DECLARE #Requests TABLE (
[AccountID] INTEGER NOT NULL,
[DebtorID] INTEGER NOT NULL,
[Seq] INTEGER NOT NULL,
[ErrorMessage] VARCHAR(500) NULL
);
IF #PrimaryDebtor = 1 OR #LetterType IN ('CUS', 'ATT') BEGIN
INSERT INTO #Requests ([AccountID], [DebtorID], [Seq])
SELECT DISTINCT [master].[number] AS [AccountID],
[Debtors].[DebtorID] AS [DebtorID],
[Debtors].[Seq] AS [Seq],
FROM #WorkFlowAcct AS [WorkFlowAcct]
INNER JOIN [dbo].[master] WITH (NOLOCK)
ON [WorkFlowAcct].[AccountID] = [master].[number]
INNER JOIN [dbo].[customer] WITH (NOLOCK)
ON [master].[customer] = [customer].[customer]
INNER JOIN [dbo].[Debtors] WITH (NOLOCK)
ON [master].[number] = [Debtors].[number]
AND [Debtors].[Seq] = [master].[PSeq]
LEFT OUTER JOIN [dbo].[DebtorAttorneys]
ON [Debtors].[DebtorID] = [DebtorAttorneys].[DebtorID];
END;
DECLARE #Street1 VARCHAR(512);
DECLARE #Street2 VARCHAR(512);
DECLARE #City VARCHAR(512);
DECLARE #Country VARCHAR(512);
DECLARE #Zip VARCHAR(512);
IF #Pref = 'Letter'
BEGIN
SET #DeliveryMethod = 'Letter';
SELECT #DeliveryAddress = [Street1] + ' ' + [Street2] + ' ' + [City] + ' ' + [Zipcode] + ' ' + [Country], #Street1 = [Street1], #Street2 = [Street2], #City = [City], #Country = [Country], #Zip = [ZipCode] FROM [Debtors] inner join #Requests AS Requests on [Debtors].[DebtorID] = Requests.[DebtorID] AND [Street1] IS NOT NULL;
IF #Street2 IS NULL
BEGIN
SET #DeliveryAddress = #Street1 + ' ' + #City + ' ' + #Zip + ' ' + #Country;
END
END
SET #DateCreated = GETDATE();
SET #JobName = 'WorkFlow_' + CAST(NEWID() AS CHAR(36)) + CAST(NEWID() AS CHAR(36)) + CAST(NEWID() AS CHAR(36)) + CONVERT(VARCHAR(50), GETDATE(), 126);
BEGIN TRANSACTION;
--Updated params for current Letter Request Table
INSERT INTO [dbo].[LetterRequest] ([AccountID], [LetterID], [LetterCode], [DeliveryMethod], [DeliveryAddress])
SELECT [Requests].[AccountID],
[Requests].[CustomerCode],
#LetterID AS [LetterID],
#LetterCode AS [LetterCode],
#DeliveryMethod AS [DeliveryMethod],
#DeliveryAddress AS [DeliveryAddress]
FROM #Requests AS [Requests]
INNER JOIN #AllowedCustomers AS [AllowedCustomers]
ON [Requests].[CustomerCode] = [AllowedCustomers].[CustomerCode]
WHERE [Requests].[ErrorMessage] IS NULL;
COMMIT TRANSACTION;
RETURN 0;

Related

How to split and replace with stored procedure?

I want to replace all e_Mail column where in #tablename with my users table (my main table).
For example:
#tablename
[name] [eMail] // columns
------------------------------------------------------
name surname blahblah#gmail.com
My users table
[name] [eMail]
----------------------------------------
name surname blahblah#hotmail.com
I want to update this row's eMail column as 'blahblah#hotmail.com' in #tablename.
What will procedure do?
1- Get first value of eMail column from #tablename
2- Split value (split char: #) and get first value (for example, if value blahblah#gmail.com, get gmail.com)
3- Search first value in users table
4- When the find value in users table, (Code must find blahblah#hotmail.com) Update eMail as blahblah#hotmail.com in #tablename
5- Get second value of eMail column from #tablename
.
.
.
So, I write a stored procedure. But this procedure is not working. Where is the problem?
Create Proc update_eMail
(#tablename nvarchar(50),
#columnname nvarchar(50))
AS
Begin
Declare #get_oldeMail nvarchar(100)
Declare #get_eMail nvarchar(100)
Declare #get_SplitValue nvarchar(100)
Declare #get_oldSplitValue nvarchar(100)
Declare #rowNumber int
Declare #users_rowNumber int
Declare #i int
Declare #j int
Declare #q_getRowNumber NVARCHAR(MAX)
Declare #q_getoldeMail NVARCHAR(MAX)
Declare #q_UpdateQuery NVARCHAR(MAX)
SET #q_getRowNumber = N'SELECT Count(ID)
FROM ' + QUOTENAME(#tablename)
EXECUTE #rowNumber = sp_executesql #q_getRowNumber
/*Set #rowNumber = (Select Count(ID) from #tablename)*/
Set #users_rowNumber = (Select Count(ID) from tblusers)
Set #i = 1
Set #j = 1
While(#i <= #rowNumber)
BEGIN
Set #q_getoldeMail = '(SELECT Lower(#columnname) FROM (
SELECT
ROW_NUMBER() OVER (ORDER BY ID) AS rownumber
,ID
,[Name]
,[Description]
,[Status]
,[AssignedTo]
,[AssignedToMail]
,[CC]
FROM' + #tablename + '
) AS ar
WHERE rownumber = #i)'
EXECUTE #get_oldeMail = sp_executesql #q_getoldeMail
Set #get_oldeMail = REPLACE(#get_oldeMail,'ı','i')
WHILE LEN(#get_oldeMail) > 0
BEGIN
IF CHARINDEX('#',#get_oldeMail) > 0
SET #get_oldSplitValue = SUBSTRING(#get_oldeMail,0,CHARINDEX('#',#get_oldeMail))
ELSE
BEGIN
SET #get_oldSplitValue = #get_oldeMail
SET #get_oldeMail = ''
END
SET #get_oldeMail = REPLACE(#get_oldeMail,#get_oldSplitValue + '#' , '')
END
While(#j <= #users_rowNumber)
BEGIN
Set #get_eMail = (SELECT Replace(Lower(eMail),'ı','i') FROM (
SELECT
ROW_NUMBER() OVER (ORDER BY ID) AS rownumber
,eMail
FROM tblusers) AS ar
WHERE rownumber = #j)
WHILE LEN(#get_eMail) > 0
BEGIN
IF CHARINDEX('#',#get_eMail) > 0
SET #get_SplitValue = SUBSTRING(#get_eMail,0,CHARINDEX('#',#get_eMail))
ELSE
BEGIN
SET #get_SplitValue = #get_eMail
SET #get_eMail = ''
END
SET #get_eMail = REPLACE(#get_eMail,#get_SplitValue + '#' , '')
END
if(#get_splitValue = #get_oldSplitValue)
begin
Set #q_UpdateQuery = 'Update ar Set ' + #columnname + ' = ' + #get_email + ' Where rownumber = ' +#i
EXECUTE sp_executesql #q_UpdateQuery
break
end
SET #j = #j+1
END
SET #i = #i+1
END
End
Thanks in advance.

Incorrect syntax near '=' while trying to call a stored procedure in T-sql

I am calling a stored procedure called Searchprocedure. I get an error at line where I am calling it. I have not made any changes to the parameters passed in the procedure and it was called just fine with same calling statement earlier.
Exec SearchProcedure #firstname = 'Simran', #middlename = 'kaur', #lastname = 'Khurana', #City = 'Delhi'
What's wrong with the syntax that is gives the error that says:
Incorrect syntax near '='
Edit:
Statement where I did :
set #sql = 'declare ' + '#Temp'+ #colVar + ' int'
exec(#sql)
select #sql as 'SQLFORDECLARATIONS
outputs
declare #TempMiddleName int
yet when I try to set value in the variable gives error that it should be declared first.
The set statement results in :
select #TempMiddleName=dbo.[MatchMiddleName](MiddleNameFromUser,MiddleNameFromTable,0)
which is what is should be yet it not able to see the declared variable
The stored procedure is as follows:
create procedure SearchProcedure
(
#firstname nvarchar(20),
#middlename nvarchar(20) = null,
#lastname nvarchar(20),
#DOB Date = null,
#SSN nvarchar(30)= null,
#ZIP nvarchar(10)= null,
#StateOfResidence nvarchar(2)= null,
#City nvarchar(20)= null,
#StreetName nvarchar(20)= null,
#StreetType nvarchar(20)= null,
#BuildingNumber int= null,
#Aptnumber nvarchar(10)= null
)
As
DECLARE #sSQL NVARCHAR(2000), #Where NVARCHAR(1000) = ' '
declare #Percent int,
#FN nvarchar(20),
#MN nvarchar(20) = null,
#LN nvarchar(20),
#DateOfB Date = null,
#SSNumber nvarchar(30)= null,
#ZIPCode nvarchar(10)= null,
#StateOfRes nvarchar(2)= null,
#CityOfRes nvarchar(20)= null,
#StreetNameRes nvarchar(20)= null,
#StreetTypeRes nvarchar(20)= null,
#BuildingNumberRes int= null,
#AptnumberRes nvarchar(10)= null
set #Percent = 0
create table #results
(
firstname nvarchar(20) not null,
middlename nvarchar(20),
lastname nvarchar(20)not null,
PercentageMatch int not null,
DOB Date,
SSN nvarchar(30),
ZIP nvarchar(10),
[State] nvarchar(2),
City nvarchar(20),
StreetName nvarchar(20),
StreetType nvarchar(20),
BuildingNumber int,
Aptnumber nvarchar(10)
)
declare c Cursor local static Read_only
for
SELECT * from dbo.Patients where firstname = #firstname
open c
fetch next from c into #FN,
#MN,
#LN,
#DateOfB,
#SSNumber,
#ZIPCode,
#StateOfRes,
#CityOfRes,
#StreetNameRes,
#StreetTypeRes,
#BuildingNumberRes,
#AptnumberRes
while ##FETCH_STATUS = 0 BEGIN
/*set #Percent = dbo.[MatchLastName](#lastname, #LN, #Percent)
set #Percent = dbo.[MatchMiddleName](#middlename, #MN, #Percent)
set #Percent = dbo.[MatchCity](#City, #CityOfRes, #Percent)*/
Exec [dbo].[OutputProcedure] #lastname, #LN, #middlename, #MN,#City, #CityOfRes, #Percent output
Insert into #results values
(#FN,#MN,#LN,#Percent, #DateOfB,#SSNumber, #ZIPCode,#StateOfRes,#CityOfRes,#StreetNameRes,#StreetTypeRes,#BuildingNumberRes,#AptnumberRes)
fetch next from c into #FN,
#MN,
#LN,
#DateOfB,
#SSNumber,
#ZIPCode,
#StateOfRes,
#CityOfRes,
#StreetNameRes,
#StreetTypeRes,
#BuildingNumberRes,
#AptnumberRes
end
select * from #results order by PercentageMatch desc
IF OBJECT_ID('tempdb..#results') IS NOT NULL DROP TABLE #results
go
OutputProcedure code is as follows:
CREATE Procedure OutputProcedure
(
#LastNameFromUser nvarchar(20) = null,
#LastNameFromTable nvarchar(20),
#MiddleNameFromUser nvarchar(20) = null,
#MiddleNameFromTable nvarchar(20) = null,
#CityFromUser nvarchar(20) = null,
#CityFromTable nvarchar(20) = null,
#Percentage int out
)
AS
BEGIN
select 'OUTPUTPROCEDURECALLED'
declare #maxvalue int
DECLARE #variableTable TABLE (
idx int identity(1,1),
matchvalue nvarchar(15))
INSERT INTO #variableTable(matchvalue) values ('MiddleName')
INSERT INTO #variableTable(matchvalue) values ('LastName')
INSERT INTO #variableTable(matchvalue) values ('City')
SELECT * FROM #variableTable
DECLARE #counter int
declare #sql nvarchar(100)
declare #sql2 nvarchar(25), #finalResult nvarchar(100)
declare #sql3 nvarchar(300), #sql4 nvarchar(15), #tempresultStore nvarchar(20), #temp int, #temp2 int, #average int
SET #counter = 1
SELECT #maxvalue = (SELECT MAX(idx) FROM #variableTable)
select #maxvalue as 'MAXVALUE'
WHILE(#counter <= #maxvalue)
BEGIN
DECLARE #colVar nvarchar(15)
SELECT #colVar = matchvalue FROM #variableTable WHERE idx = #counter
set #sql = 'declare ' + '#Temp'+ #colVar + ' int'
exec(#sql)
select #sql as 'SQLFORDECLARATIONS'
/*set #temp = CHARINDEX(' ',#sql)
select #temp as 'resultofcharindex'
set #temp2 = LEN(#sql) - (#temp)
SELECT #temp2 AS 'AFTERADDING1'
set #tempresultStore = right(#sql, #temp2)*/
set #tempresultStore = 'Temp'+#colVar
SELECT #tempresultStore AS 'FINALCUTPART'
set #sql3 = 'set ' + ' ' + #tempresultStore + '=' + 'dbo.[Match' + #colVar + '](' + #colVar + 'FromUser' + ',' + #colVar + 'FromTable' + ',' + '0)'
EXEC(#sql3)
select #sql3 as 'check sql query formed'
set #finalResult = #finalResult + #tempresultStore
select #finalResult as 'SUM'
SET #counter = #counter + 1
select #counter as 'COUNTERVALUE'
END
set #Percentage = #finalResult/#maxvalue
SELECT #Percentage AS 'FINALRESULT'
RETURN
END
--Setting variable in Dynamic SQL
DECLARE
#sql NVARCHAR(MAX),
#Name NVARCHAR(100)
SET #Name = '#B2E0EB1A'
SET #sql =
'
DECLARE #MyVar NVARCHAR(100)
SELECT TOP 1 #MyVar = name FROM sys.objects WHERE name LIKE ''%a''--Escaping single quote with double quote
PRINT #MyVar
'
EXEC(#sql)
SET #sql =
'
DECLARE #MyVar NVARCHAR(100)
SET #MyVar = '''+(SELECT TOP 1 name FROM sys.objects WHERE name LIKE '%a')+'''--Escaping single quote with double quote
PRINT #MyVar
'
EXEC(#sql)
SET #sql =
'
DECLARE #MyVar NVARCHAR(100)
SET #MyVar = '''+#Name+'''--Escaping single quote with double quote
PRINT #MyVar
'
EXEC(#sql)
SET #sql =
'
DECLARE #MyVar NVARCHAR(100)
SET #MyVar = ''#B2E0EB1A''--Escaping single quote with double quote
PRINT #MyVar
'
EXEC(#sql)
If you want to get output variable from your dynamic query you have to use sp_executesql procedure instead of EXEC()
Study this code
DECLARE #DynamicSQLOutput NVARCHAR(100)
DECLARE #SQL nvarchar(500);
DECLARE #ParmeterDefinition nvarchar(500);
--in this variabe you write the variables which you want to be declared in the dynamic sql without using the declare
SET #ParmeterDefinition = N'#FinalOutputResultInDynamicSQL NVARCHAR(100) OUTPUT';
--here you write your dynamic code
SELECT #SQL = N'SET #FinalOutputResultInDynamicSQL = ''test'' '
EXEC sp_executesql
#SQL, --Execute code
#ParmeterDefinition, -- Define Parameters
#FinalOutputResultInDynamicSQL = #DynamicSQLOutput OUTPUT --Get output
--Note that #FinalOutputResultInDynamicSQL is only defined in #ParmeterDefinition but not outside of the dynamic sql
PRINT #DynamicSQLOutput;
I think too many things wrong in your Dynamic sql. I found one
SET #sql3 = 'set ' + ' ' + #tempresultStore + ' = ' + 'dbo.[Match'
+ #colVar + '](' + #colVar + 'FromUser' + ',' + #colVar
+ 'FromTable' + ',' + '0)'
In the above code instead of Set use Select. Looks like you are selecting from a UDF. Try this
SET #sql3 = 'Select ' + ' ' + #tempresultStore + ' = ' + 'dbo.[Match'
+ #colVar + '](' + #colVar + 'FromUser' + ',' + #colVar
+ 'FromTable' + ',' + '0)'
Note : To debug Dynamic Sql before Exec #sql just use print #sql to check the syntax and other stuff in generated sql
I can't find any error and can run the exec without anerror message.
Edit: After I created the (now avialbe) output procedure and uncomment its call, I'm getting the error too...
Still investigating
Edit2:
In the Output procedure you have to use
set #sql = 'declare ' + '#Temp'+ #colVar + ' int' (# before Temp) and
set #sql3 = 'set ' + ' #' + #tempresultStore" (additional # after the 'set'.
Btw: you can exec more than one statement in Dynamic SQL so you could use f.e. exec (#sql + '; ' + #sql3);

Passing parametrs to dynamic query

I have a stored procedure as following, I need to pass paramters to the dynamic pivot. My query runs, I just need to do some filtering based on the passed parameters
-- AND (#SelectedSystemIDs IS NULL OR System.ID IN(select * from dbo.SplitInts_RBAR_1(#SelectedSystemIDs, ',')))
--AND ((#PlatformID IS NULL) OR (System.PlatformID = #PlatformID) OR (#PlatformID = 12 AND System.PlatformID <= 2))
-- AND (ServiceEntry.ServiceDateTime between #StartDate and #EndDate)
so I want to add the above criteria, how could achieve that?
ALTER PROCEDURE [dbo].[spExportStuff]
(#StartDate datetime,
#EndDate datetime,
#SelectedSystemIDs nvarchar (2000) = NULL,
#SelectedTsbIDs nvarchar (2000) = NULL,
#UserRoleID int
)
AS
DECLARE #InstrumentType int = NULL
DECLARE #PlatformID int = null
IF (#SelectedSystemIDs = '')
begin
SET #SelectedSystemIDs = NULL
END
IF (#SelectedTsbIDs = '')
begin
SET #SelectedTsbIDs = NULL
END
IF(#UserRoleID = 1)
BEGIN
SET #PlatformID = 1
END
IF(#UserRoleID = 2)
BEGIN
SET #PlatformID = 2
END
IF (#UserRoleID = 3)
BEGIN
SET #PlatformID = 12
END
IF(#UserRoleID = 4)
BEGIN
SET #PlatformID = 3
END
IF(#UserRoleID = 5)
BEGIN
SET #PlatformID = 4
END
IF(#UserRoleID = 6)
BEGIN
SET #PlatformID = NULL
END
DECLARE #PivotColumnHeaders NVARCHAR(MAX)
SELECT #PivotColumnHeaders =
COALESCE(
#PivotColumnHeaders + ',[' + cast(SystemFullName as Nvarchar) + ']',
'[' + cast(SystemFullName as varchar)+ ']'
)
FROM System
DECLARE #PivotTableSQL NVARCHAR(MAX)
SET #PivotTableSQL = N'
SELECT *
FROM (
SELECT
TSBNumber [TSBNumber],
SystemFullName,
ClosedDate
FROM ServiceEntry
INNER JOIN System
ON ServiceEntry.SystemID = System.ID
Group By TSBNumber, SystemFullName, ClosedDate
) AS PivotData
PIVOT (
max(ClosedDate)
FOR SystemFullName IN (
' + #PivotColumnHeaders + '
)
) AS PivotTable
'
EXECUTE(#PivotTableSQL)
you can construct the required criteria as another input to the stored procedure and append it to the dynamic query
ALTER PROCEDURE [dbo].[spExportStuff]
(#StartDate datetime,
#EndDate datetime,
#SelectedSystemIDs nvarchar (2000) = NULL,
#SelectedTsbIDs nvarchar (2000) = NULL,
#UserRoleID int,
#WhereClause varchar(max) -> this is the new parameter.
)
DECLARE #PivotTableSQL NVARCHAR(MAX)
SET #PivotTableSQL = N'
SELECT *
FROM (
SELECT
TSBNumber [TSBNumber],
SystemFullName,
ClosedDate
FROM ServiceEntry
INNER JOIN System
ON ServiceEntry.SystemID = System.ID
Group By TSBNumber, SystemFullName, ClosedDate
) AS PivotData
PIVOT (
max(ClosedDate)
FOR SystemFullName IN (
' + #PivotColumnHeaders + '
)
) AS PivotTable
' + #WhereClause -> you can append the where clause here.
EXECUTE(#PivotTableSQL)

Dynamic TSQL Query output as XML

I have a dynamic TSQL query that is working perfectly. However, before I had it dynamic like this I was returning it as an XML output.
How can I do the same with my output now? I need the results in an XML format.
ALTER PROCEDURE [dbo].[empowermentFetchSubmissions2]
#category INT=NULL, #department INT=NULL, #startDate DATE=NULL, #endDate DATE=NULL, #empID VARCHAR (60)=NULL, #submissionID INT=NULL, #inVoting INT=NULL, #pastWinners INT=NULL
AS
DECLARE #sSQL AS NVARCHAR (3000),
#Where AS NVARCHAR (1000) = ' (1=1) ';
BEGIN
SET NOCOUNT ON;
BEGIN
SET #sSQL = 'SELECT A.[submissionID],
A.[subEmpID],
A.[nomineeEmpID],
A.[nomineeDepartment],
CONVERT (VARCHAR (10), A.[submissionDate], 101) AS submissionDate,
A.[situation],
A.[task],
A.[action],
A.[result],
A.[timestamp],
A.[statusID],
A.[approver],
A.[approvalDate],
B.[FirstName] + '' '' + B.[LastName] AS nomineeName,
B.[ntid] AS nomineeNTID,
B.[qid] AS nomineeQID,
C.[FirstName] + '' '' + C.[LastName] AS submitName,
C.[ntid] AS submitNTID,
D.[categoryName],
(SELECT CAST
(CASE WHEN EXISTS (SELECT TOP (1) submissionID
FROM empowermentEntries
WHERE sessionID = (SELECT TOP (1) sessionID
FROM empowermentSessions
WHERE status = 1
AND CAST(GETDATE() as date) >= startDate
AND CAST(GETDATE() as date) <= endDate ) AND submissionID = A.[submissionID])
THEN ''true''
ELSE ''false''
END AS XML) AS inVoting)
FROM empowermentSubmissions AS A
INNER JOIN
empTable AS B
ON A.[nomineeEmpID] = B.[empID]
INNER JOIN
empTable AS C
ON A.[subEmpID] = C.[empID]
INNER JOIN
empowermentCategories AS D
ON A.[categoryID] = D.[catID]';
IF #category IS NOT NULL
SET #Where = #Where + ' AND A.[categoryID] = #_category';
IF #department IS NOT NULL
SET #Where = #Where + ' AND A.[nomineeDepartment] = #_department';
IF #startDate IS NOT NULL
SET #Where = #Where + ' AND A.[submissionDate] >= #_startDate';
IF #endDate IS NOT NULL
SET #Where = #Where + ' AND A.[submissionDate] <= #_endDate';
IF #empID IS NOT NULL
SET #Where = #Where + ' AND A.[nomineeEmpID] = #_empID';
IF #submissionID IS NOT NULL
SET #Where = #Where + ' AND A.[submissionID] = #_submissionID';
IF #inVoting IS NOT NULL
SET #Where = #Where + ' AND A.[submissionID] IN (SELECT submissionID
FROM empowermentEntries
WHERE sessionID = (SELECT TOP (1) sessionID
FROM empowermentSessions
WHERE status = 1
AND CAST(GETDATE() as date) >= startDate
AND CAST(GETDATE() as date) <= endDate )
AND submissionID = A.[submissionID])';
IF #pastWinners IS NOT NULL
SET #Where = #Where + ' AND A.[submissionID] IN (SELECT E.[submissionID]
FROM empowermentEntries as E
JOIN empowermentWinners as F
ON E.[entryID] = F.[entryID]
WHERE submissionID = A.[submissionID])';
IF LEN(#Where) > 0
SET #sSQL = #sSQL + ' WHERE ' + #Where;
EXECUTE sp_executesql #sSQL, N'#_category INT, #_department INT, #_startDate DATE, #_endDate DATE, #_empID VARCHAR(60), #_submissionID INT, #_inVoting INT, #_pastWinners INT', #_category = #category, #_department = #department, #_startDate = #startDate, #_endDate = #endDate, #_empID = #empID, #_submissionID = #submissionID, #_inVoting = #inVoting, #_pastWinners = #pastWinners;
END
END
You need to take your existing Dynamic SQL, added the FOR XML... to the end, wrap that in parenthesis, and set that value to a variable which is used as OUTPUT for the sp_executesql. For example:
DECLARE #SQL NVARCHAR(MAX),
#Results XML;
SET #SQL = N'
SET #Out = (SELECT * FROM sys.objects FOR XML AUTO);
';
EXEC sp_executesql #SQL, N'#Out XML OUTPUT', #Out = #Results OUTPUT;
SELECT #Results;
So declare a new variable at the top for:
DECLARE #Results XML;
Then just before your EXECUTE sp_executesql #sSQL... line, do the following:
SET #sSQL = N'SET #Results = (' + #sSQL + N' FOR XML {xml options});';
Then update your param spec for sp_executesql to include, at the end:
N'#_category INT, ..., #Results XML OUTPUT'
And add the following to the end of the sp_executesql:
#_category = #category, ..., #Out = #Results OUTPUT

Having issues with UPDATE command

Using this SP I keep getting an error on the UPDATE statement indicating that I have conversion problem or something. But ID is an integer in all of my tables....
Conversion failed when converting the varchar value 'UPDATE tblLangenUS SET [lang_String] = ' - asdfgsdfg', [prev_LangString] = ' ', [needsTranslation] = 'false' WHERE [ID] = '' to data type int.
#currTable varchar(100),
#ID int,
#short_Text varchar(250),
#brief_Descrip varchar(250) = Null,
#needsTranslation varchar(10) = Null,
#prev_LangString varchar(250) = Null,
#lang_String varchar(250) = Null,
#original_lang_String varchar(250) = Null,
#StringID_from_Master varchar(250),
#GUID varchar(250) = Null
/*
*/
AS
SET NOCOUNT ON;
DECLARE #userTable AS VARCHAR(200);
SET #userTable = #currTable
DECLARE #submitDate1 DATETIME;
SET #submitDate1 = GETDATE()
SET #prev_LangString = #original_lang_String
SET #needsTranslation = 'false'
DECLARE #sql varchar(max)
-- Establish update to the language tabel of user and prepare to search DB for all strings that will need to be updated.
BEGIN
SET #sql = 'UPDATE ' + #currTable + ' SET [lang_String] = ''' + #lang_String + ''', [prev_LangString] = ''' + #prev_LangString + ''', [needsTranslation] = ''' + #needsTranslation + ''' WHERE [ID] = ''' + #ID + '''; '
EXEC #sql
#sql = ''
END
BEGIN
DECLARE usedIN_DBScursor CURSOR
FOR
SELECT tblUniquetblStringsMaster_ID, Database_Name, dbKeyID_ofStringName
FROM tblDBUsage
WHERE (tblUniquetblStringsMaster_ID = #StringID_from_Master );
-- Declare the variables to store the values returned by FETCH.
DECLARE #tblUniquetblStringsMaster_ID AS INT;
DECLARE #dbKEYID as INT;
DECLARE #dbName as varchar(100);
OPEN usedIN_DBScursor;
-- Perform the first fetch and store the values in variables.
-- Note: The variables are in the same order as the columns
-- in the SELECT statement.
FETCH NEXT FROM usedIN_DBScursor
INTO #tblUniquetblStringsMaster_ID, #dbName, #dbKEYID;
-- Check ##FETCH_STATUS to see if there are any more rows to fetch.
WHILE ##FETCH_STATUS = 0
BEGIN
-- Update pending strings table with translation.
BEGIN
INSERT INTO tblPendingDBUpdates
(stringMasterID, databaseName, databaseStringID, englishText, foreignLangText, submitDate, GUID)
VALUES (#StringID_from_Master, #dbName, #dbKEYID, #short_Text, #lang_String, #submitDate1, #GUID);
END
-- SET #sql = ''
-- This is executed as long as the previous fetch succeeds.
FETCH NEXT FROM usedIN_DBScursor
INTO #tblUniquetblStringsMaster_ID, #dbName, #dbKEYID;
END
CLOSE usedIN_DBScursor;
DEALLOCATE usedIN_DBScursor;
END
RETURN
If the ID is an int, you must CAST it to an nvarchar
SET #sql = 'UPDATE ' + #currTable + ' SET [lang_String] = ''' + #lang_String + ''', [prev_LangString] = ''' + #prev_LangString + ''', [needsTranslation] = ''' + #needsTranslation + ''' WHERE [ID] = ''' + CAST(#ID as nvarchar(10)) + '''; '
Otherwise, you are trying to add a string and an integer together, which won't work.
Notice this part:
' WHERE [ID] = ''' + CAST(#ID as nvarchar(10)) + '''
I think you must also change your EXEC syntax to:
EXEC(#sql)