Why do I get a "must declare scalar variable" error in dynamic SQL? - sql

I am trying to use Dynamic SQL when setting a value to a variable, but it doesn't work. However, the same statement does work in regular SQL. This is the code:
DECLARE #sqlcmd nchar(1024);
DECLARE #DBName nchar(30) = 'DB_1016a'
DECLARE #UserKey int = 0;
DECLARE #UserID nchar(30) = 'DBCLIENT\StudentA'
set #sqlcmd = 'set #UserKey = (SELECT [Key] from ' + rtrim(ltrim(#DBName)) + '.dbo.userlist where ID = ''' + rtrim(ltrim(#UserID)) + ''')'
print(#sqlcmd)
exec(#sqlcmd)
print('stuff1')
print('['+rtrim(ltrim(cast(#UserKey as nchar(4))))+']')
print('stuff2')
And this is what it returns:
set #UserKey = (SELECT [Key] from DB_1016a.dbo.userlist where ID = 'DBCLIENT\StudentA')
*Msg 137, Level 15, State 1, Line 30
Must declare the scalar variable "#UserKey".*
stuff1
[0]
stuff2
What am I doing wrong?

You need to bind an output parameter in the dynamic SQL batch and assign your local variable to the parameter. Like this:
DECLARE #sqlcmd nchar(1024);
DECLARE #DBName nchar(30) = 'DB_1016a'
DECLARE #UserKey int;
DECLARE #UserID nchar(30) = 'DBCLIENT\StudentA'
set #sqlcmd = 'set #UserKey = (SELECT [Key] from ' + rtrim(ltrim(#DBName)) + '.dbo.userlist where ID = ''' + rtrim(ltrim(#UserID)) + ''')'
print(#sqlcmd)
exec sp_executesql #sqlcmd, N'#UserKey int out', #UserKey = #UserKey output
print('stuff1')
print('['+rtrim(ltrim(cast(#UserKey as nchar(4))))+']')
print('stuff2')

You're dealing with a scope issue. The statement contained in #sqlcmd is in a different execution scope than that where you declare #UserKey when you run it with exec.

Related

SQL Server output param truncated where it is too long

I have 4 stored procedures.
The following is used to be invoked by C#:
ALTER PROCEDURE [dbo].[sp_retrieveResourceShell]
AS
BEGIN
SET NOCOUNT ON
DECLARE #result NVARCHAR(MAX)
EXEC [dbo].[sp_retrieveResTree]
#pid = NULL,
#ret = #result OUTPUT
***select*** #result
END
These are internal stored procedures:
ALTER PROCEDURE [dbo].[sp_retrieveResTree]
(#pid UNIQUEIDENTIFIER,
#ret NVARCHAR(MAX) OUTPUT)
AS
BEGIN
DECLARE #mdlId UNIQUEIDENTIFIER,
#mdlGroup NVARCHAR(MAX)
DECLARE mdlCursor CURSOR FOR
......
DECLARE #subRet NVARCHAR(MAX),
#viewRet NVARCHAR(MAX)
EXEC [dbo].[sp_retrieveResTree]
#pid = #mdlId,
#ret = #subRet OUTPUT
EXEC dbo.sp_retrieveResView
#mdlId = #mdlId,
#ret = #viewRet OUTPUT
SET #mdlGroup = #mdlGroup + FORMATMESSAGE('{"Id":"%s","Name":"%s","Subs":%s,"Views":%s},'...)
.......
SET #ret = FORMATMESSAGE('[%s]',#mdlGroup)
END
ALTER PROCEDURE [dbo].[sp_retrieveResView]
(#mdlId UNIQUEIDENTIFIER,
#ret NVARCHAR(MAX) OUTPUT)
AS
BEGIN
SET #ret = FORMATMESSAGE('[%s]',#viewGroup)
END
When I invoke sp_retrieveResourceShell like this:
DECLARE #return_value int
EXEC #return_value = [dbo].[sp_retrieveResourceShell]
SELECT 'Return Value' = #return_value
I can get a truncated string with ellipsis at the string tail.
how to get the full string without ellipsis?
update
Changed formatmessage function to string concatenation likes
SET #mdlGroup = #mdlGroup + '{"Id":"' + CAST(#mdlId AS CHAR(36))+ '","Name":"' + #mdlName + '","Subs":' + #subRet + ',"Views":' + #viewRet +'},'
when using string concatenation , likes
SET #ret = N'[' + #mdlGroup + N']'
and refernce to [n]varchar(max) + [n]varchar(max)
i got the right full string . Thanks to #MartinSmith at the same time .

SQL Server dynamic procedure 2

USE KronosNET22
GO
Create procedure eventossucursales4
#id nvarchar(max),
#dia nvarchar(max)
as
begin
declare #sqlstring nvarchar(max)
set #sqlstring = 'Select Code From ' + #dia + ' WHERE idObject = ''' + #id + ''' AND (CODE = ''TFHi2'' OR CODE = ''E603'')'
EXEC sp_executesql #sqlstring, #id,#dia
end
GO
Execute eventossucursales4 'E4211537-09CD-45F2-BB5F-F20F642DE676','ObjectSignal_2016_05_23 '
Error:
Mens. 102, Nivel 15, Estado 1, LĂ­nea 1
Sintaxis incorrecta cerca de 'E4211537'.
Can someone help me to figure it out why its showing a mistake in the declaration of the variable?
You could eliminate passing the parameters as someone commented. If you want to make it work as is, you need to add the parameter list. I was able to get it working this way.
alter procedure eventossucursales4
#id nvarchar(max),
#dia nvarchar(max)
as begin
declare #sqlstring nvarchar(max)
declare #ParmDefinition nvarchar(500) = '#dia nvarchar(max), #id nvarchar(max)'
set #sqlstring = 'Select Code From ' + #dia + ' WHERE idObject = ''' + #id + ''' AND (CODE = ''TFHi2'' OR CODE = ''E603'')'
exec sp_executesql #sqlstring, #ParmDefinition, #id = #id, #dia = #dia
end
GO
Execute eventossucursales4 'E4211537-09CD-45F2-BB5F-F20F642DE676','ObjectSignal_2016_05_23 '

How to parse an array in sql server

I created a stored procedure that looks like this.
CREATE PROCEDURE [EXP_RfPickAfter] (
#SESSIONVALUE xml,
#WorkDSArray nvarchar(max),
#UserSignonDS nvarchar(max),
#Direction nvarchar(max),
#ImmediateCount nvarchar(max),
#CCWorkUnit nvarchar(max),
#PartialPick nvarchar(max),
#RETURNVALUE nvarchar(max) output
)
AS
SET NOCOUNT ON;
#workDSArray has this long string in it
924WORK0924841SEQUENCE8410841842EQUIPMENT_LOC842842843PARENT_LOGISTICS_
UNIT843843844REFERENCE_TYPE844Order844845INVENTORY_AT_
PD845845846FROMVER846None846847INTERNAL_NUM8476851842847848START_
DATE_TIME848848849INCHKDIG849849850TOTAL_VOLUME8500850851
TO_LOC851SHIP-1851852INTERNAL_NUM_TYPE852Shipment852853
WEIGHT_UM853LB853854COMPANY854SHOS854855QUANTITY_UM855CS855856OUTGOING_
PD_LOC856856857WORK_TYPE857LPNPick857858END_DATE_TIME858858859
ACTUALFROMWHS859L455859860LOT860860861WORK_ZONE1861861862
TOCONTAINERID8621862863INVER863863864TRACK_CONTAINERS864N864865
TO_LOC_INV_ATTRIBUTES_ID865865866CYCLE_COUNT866866867
LAUNCH_NUM86716949391867868ACTUALTOLOC868-jisavm3868869
FROM_CHECK_DIG869869870FROM_WHS870L455870871
WORK_GROUP871Picking871872INTERNAL_LINE_NUM187232612518872873
VOLUME_UM873873874ACTUALFROMLOC874NF-1-F-28-1874875
INTERNAL_REQ_NUM87520774185875876TO_WHS876L455876877
INTERNAL_LINE_NUM87732612518877878TREE_UNIT87826385537878879
INWRKZONE879879880PUTLOC880SHIP-1880881CONTAINER_ID88116489660881882
INTERNAL_CONTAINER_NUM88226385537882883FROMTRKCONT883Y883884
PARENT_CONTAINER_NUM8840884885CONVERTED_QTY_UM885CS885886
ACTUALTOWHS886L455886887OUTWRKZONE887887888
VERIFICATION_METH888None888889USER_DEF4889 L455-RS 2889890
REFERENCE_ID890XKJNNLJN890891LOGISTICS_UNIT89116489660891892
MESSAGE_ID892892893PICKLOC893NF-1-F-28-1893894
CURRENTLOC894F894895TREE_UNIT_ID89516489660895897
TOCONTAINERID089716489660897898TOTAL_WEIGHT8981898899
TOTAL_VALUE8990899900TO_CHECK_DIG900900901OUTCHECKDIG901901902
TO_QTY9020902903INTRKCONT903903904FROM_LOC_INV_ATTRIBUTES_ID904904905
INTERNAL_INSTRUCTION_NUM90520699485905906ITEM_DESC906MSF21D4MDE -
Refrigerator906907ITEM907SHOS-STOCK907908
COMPLETEDBYUSER908jisavm3908909
TRANSPORT_CONT_ID90916489660909910OUTTRKCONT910910911ACCOUNT911
Store #9449911912INCOMING_PD_LOC912912913INVENTORY_TRACKING913Y913914
LOCATION_CLASS914Shipping Dock914915FROM_QTY9151915916OUTVERMETH916916917
CONVERTED_QTY9171917918QUANTITY9181918919
PARENT_INSTR91920699484919920
FROM_LOC920NF-1-F-28-1920921WORK_ZONE921W-
Returns921922WORK_UNIT92216489660922923QTY
CONFIRMED9231923924925WORK9251925
I am trying to parse containerID and its value from this string and use it in a select statement in my stored procedure, but I am unsure how to parse only the containerID.
Any help would be appreciated
This is what I did to get the right ID I had to trigger off of something else. This is not ideal because I don't know if the string will change. If anybody knows a better way please post and thank you #ymuribbi you helped me out a ton. I edited this to show my full solution just in case someone else runs into this issue.
DECLARE #WorkDSArray nvarchar(max);
SET #WorkDSArray= '924WORK0924841SEQUENCE8410841842EQUIPMENT_LOC842842843PARENT_LOGISTICS_UNIT843843844REFERENCE_TYPE844Order844845INVENTORY_AT_PD845845846FROMVER846None846847INTERNAL_NUM8476851842847848START_DATE_TIME848848849INCHKDIG849849850TOTAL_VOLUME8500850851TO_LOC851SHIP-1851852INTERNAL_NUM_TYPE852Shipment852853WEIGHT_UM853LB853854COMPANY854SHOS854855QUANTITY_UM855CS855856OUTGOING_PD_LOC856856857WORK_TYPE857LPN Pick857858END_DATE_TIME858858859ACTUALFROMWHS859L455859860LOT860860861WORK_ZONE1861861862TOCONTAINERID8621862863INVER863863864TRACK_CONTAINERS864N864865TO_LOC_INV_ATTRIBUTES_ID865865866CYCLE_COUNT866866867LAUNCH_NUM86716949391867868ACTUALTOLOC868-jisavm3868869FROM_CHECK_DIG869869870FROM_WHS870L455870871WORK_GROUP871Picking871872INTERNAL_LINE_NUM187232612518872873VOLUME_UM873873874ACTUALFROMLOC874NF-1-F-28-1874875INTERNAL_REQ_NUM87520774185875876TO_WHS876L455876877INTERNAL_LINE_NUM87732612518877878TREE_UNIT87826385537878879INWRKZONE879879880PUTLOC880SHIP-1880881CONTAINER_ID88116489660881882INTERNAL_CONTAINER_NUM88226385537882883FROMTRKCONT883Y883884PARENT_CONTAINER_NUM8840884885CONVERTED_QTY_UM885CS885886ACTUALTOWHS886L455886887OUTWRKZONE887887888VERIFICATION_METH888None888889USER_DEF4889 L455-RS 2889890REFERENCE_ID890XKJNNLJN890891LOGISTICS_UNIT89116489660891892MESSAGE_ID892892893PICKLOC893NF-1-F-28-1893894CURRENTLOC894F894895TREE_UNIT_ID89516489660895897TOCONTAINERID089716489660897898TOTAL_WEIGHT8981898899TOTAL_VALUE8990899900TO_CHECK_DIG900900901OUTCHECKDIG901901902TO_QTY9020902903INTRKCONT903903904FROM_LOC_INV_ATTRIBUTES_ID904904905INTERNAL_INSTRUCTION_NUM90520699485905906ITEM_DESC906MSF21D4MDE - Refrigerator906907ITEM907SHOS-STOCK907908COMPLETEDBYUSER908jisavm3908909TRANSPORT_CONT_ID90916489660909910OUTTRKCONT910910911ACCOUNT911Store #9449911912INCOMING_PD_LOC912912913INVENTORY_TRACKING913Y913914LOCATION_CLASS914Shipping Dock914915FROM_QTY9151915916OUTVERMETH916916917CONVERTED_QTY9171917918QUANTITY9181918919PARENT_INSTR91920699484919920FROM_LOC920NF-1-F-28-1920921WORK_ZONE921W-Returns921922WORK_UNIT92216489660922923QTYCONFIRMED9231923924925WORK9251925'
DECLARE #ContainerID integer;
SET #ContainerID = CHARINDEX('TREE_UNIT_ID', #WorkDSArray);
DECLARE #ID nvarchar(max);
SET #ID = SUBSTRING(#WorkDSArray, #ContainerID,300)
SELECT #ID;
DECLARE #ActualContainerID nvarchar(max);
SET #ActualContainerID = SUBSTRING(#ID, 54, 9)
SET #ActualContainerID = REPLACE(#ActualContainerID, CHAR(31), '')
DECLARE #User integer
DECLARE #UserID nvarchar(max)
SET #User = CHARINDEX('COMPLETEDBYUSER', #WorkDSArray);
SET #UserID = SUBSTRING(#WorkDSArray, #User,27)
DECLARE #ActualUserID nvarchar(max);
SET #ActualUserID = SUBSTRING(#UserID, 20, 8)
SET #ActualUserID = REPLACE(#ActualUserID, CHAR(31), '')
DECLARE #Shipment nvarchar(max)
SET #Shipment = (SELECT CASE WHEN SH.COMPANY = 'SHOS' THEN '' ELSE SH.SHIPMENT_ID + '|' +
SH."ROUTE" + '|' +
SH."STOP" + '|' +
SH.COMPANY + '|' +
LEFT(SH.CUSTOMER_NAME,25) + '|' +
LEFT(SH.SHIP_TO_ADDRESS1,25) + '|' +
CASE WHEN SH.SHIP_TO_ADDRESS2 <> '' THEN SH.SHIP_TO_ADDRESS2 + '|'
ELSE '' END +
LEFT(SH.SHIP_TO_CITY,25) + '|' +
LEFT(SH.SHIP_TO_STATE,25) + '|' +
LEFT(SH.SHIP_TO_POSTAL_CODE,25) END
FROM SHIPMENT_HEADER SH
JOIN SHIPPING_CONTAINER SC
ON SC.INTERNAL_SHIPMENT_NUM = SH.INTERNAL_SHIPMENT_NUM
WHERE SC.CONTAINER_ID = #ActualContainerID)
DECLARE #ShipmentID nvarchar(max)
SET #ShipmentID = SUBSTRING(#Shipment,0,9)
--select top 1 device_name from dbo.DOCUMENT_ROUTING where document_type = 'HJBT_REC' and user_name = #user
INSERT INTO [jbh].[PRT_REQ_WRK]
([REQ_REF_TYP], [REQ_REF_I], [PRT_DVC_NM], [REQ_TMPL_NM], [REQ_VAL], [PRT_STT], [PRT_PRS_TYP], [PRT_Q], [CRT_S], [CRT_UID], [CRT_PGM_C], [LST_UPD_S], [LST_UPD_UID], [LST_UPD_PGM_C])
VALUES (
#ShipmentID, --[REQ_REF_TYP]
'123abc', --[REQ_REF_I]
'LB01885', --[PRT_DVC_NM]
'HJBT_Shipping_Label.lbl', --[REQ_TMPL_NM]
#Shipment, --[REQ_VAL]
0, --[PRT_STT]
'LABEL', --[PRT_PRS_TYP]
1, --[PRT_Q]
CURRENT_TIMESTAMP, --[CRT_S]
#ActualUserID, --[CRT_UID]
'WMSPrintService', --[CRT_PGM_C]
CURRENT_TIMESTAMP, --[LST_UPD_S]
'JISAVM3', --[LST_UPD_UID]
'WMSPrintService') --[LST_UPD_PGM_C]
As #hogan stated in his comment, you can use string operators for extraction with some while and if-else statements
-- I am editing my answer.
To retrieve the container ID you use a store procedure like this:
create proc getid (#string varchar(max)) as
declare #containerIdIndex int = (select charindex('CONTAINER_ID',#string))
declare #internalContainerIndex int = (select(Charindex('INTERNAL_CONTAINER', #string)))
declare #range int = #internalContainerindex-#containerIdindex+12
declare #start int = #containerIdIndex+12 --12 is to pass the 'Container_ID'
declare #containerId varchar(max)
set #containerId = substring(#string,#start,#range)
print #containerId

Store the result of a Dynamic Query in a variable

I know this question has been asked, and I already found some solutions in internet.. but I still can not make it work properly.
So.. I have to make a SELECT query and store the result in a variable (I DONT want a table variable).
My problem is that the name of the table is also a variable. The table name changes accordingly to a WHILE, here is my code:
DECLARE #numRecord INT;
DECLARE #maxMacNumber INT;
SET #maxMacNumber = 500;
DECLARE #mac INT;
SET #mac = 0;
DECLARE #res FLOAT;
DECLARE #ap INT;
SET #ap = 0;
DECLARE #apString VARCHAR(2);
DECLARE #numRecordString VARCHAR(20);
DECLARE #tablename VARCHAR(500);
DECLARE #sql NVARCHAR(500);
DECLARE #varDefinition NVARCHAR(200);
WHILE #mac <= #maxMacNumber
BEGIN
SET #numRecord = 6 + #mac * 390;
SET #ap = 0;
WHILE #ap < 2
BEGIN
SELECT #apString = CONVERT(VARCHAR,#ap);
SELECT #numRecordString = CONVERT(VARCHAR, #numRecord);
SELECT #rssiString = CONVERT(VARCHAR, #rssi);
SET #tablename = 'APDB.dbo.AP' + #apString;
SET #sql = 'SELECT RSSI FROM ' + #tablename + ' WHERE ID=' + #numRecordString;
SET #varDefinition = N'#res FLOAT OUTPUT';
EXEC sp_executesql #sql, #varDefinition, #res = #res OUTPUT;
PRINT #res;
-- HERE I WILL DO SOMETHING WITH #res
END;
END;
The problem is that it doesn't print anything when I do PRINT #res...
This is the relevant SQL code:
SET #sql = 'SELECT RSSI FROM ' + #tablename + ' WHERE ID=' + #numRecordString;
SET #varDefinition = N'#res FLOAT OUTPUT';
EXEC sp_executesql #sql, #varDefinition, #res = #res OUTPUT;
PRINT #res;
You are never setting #res in the SQL. Try this:
SET #sql = 'SELECT #res = RSSI FROM ' + #tablename + ' WHERE ID=' + #numRecordString;
SET #varDefinition = N'#res FLOAT OUTPUT';
EXEC sp_executesql #sql, #varDefinition, #res = #res OUTPUT;
PRINT #res;

increase counter while using exec

I want to use a counter in a way like the below one:
exec
('begin insert into ' + #temp07 + ' (FileID,FileName)
Select aof_id,aof_fileName from PaFi07(' + #partId + ');
sp_executesql #sqlCounter, N'#intCount int output, #intConst int, #intCount = #intCount output, #intConst = #intConst
end')
so how can i let the counter work?
any suggestion that the counter work inside this EXEC command
THANX
You cannot EXEC them as EXEC runs in its own scope so the variable identifiers have no meaning.
You can instead declare them as ints, pass them to sp_executesql along with a statement string and return the result as an output;
declare #sql nvarchar(256) = 'SET #intCount = #intCount + #intConst'
EXEC sp_executesql #sql,
N'#intCount int output, #intConst int',
#intCount = #intCount output,
#intConst = #intConst
select #intCount
>6
There are several errors in your snippet:
First of all, you are declaring your variables as varchar(10), while you are intending to use them as numbers. They should be declared as smallint, int or bigint.
Then you are composing a string using those varchar variables and trying to add 1 to the value stored in #inCount with an addition of the number 1.
Since your variables are strings and not numbers, the + symbols tries to concatenate them.
To realize about your error, first, you should convert the number 1 to a string, writing the EXEC like this:
exec ('SET ' + #intCount + ' = ' + #intCount + '1')
Once you have done that, just remove the EXEC and assign the string you are concatenating to a new string variable. So:
DECLARE #composedQuery varchar(1000)
SET #composedQuery = 'SET ' + #intCount + ' = ' + #intCount + '1'
SELECT #composedQuery
You will see a result like this:
SET 5 = 51
For sure, this is not what you are intending to execute with EXEC, isn't it? :)
The correct solution has been given to you in other answers. I rewrite the full snippet:
declare #intCount int
declare #intConst int
set #intCount = 5
set #intConst = 1
SET #intCount = #intCount + 1
--OR
SET #intCount = #intCount + #intConst
You don't need exec for that:
set #inCount = #intCount + #intConst
If you want to use exec, you would use the name of the variables in the string, not the values:
exec('set #inCount = #intCount + #intConst')
Edit:
For the new question; you would concatenate the values into the string:
exec
('begin insert into ' + #temp07 + ' (FileID,FileName)
Select aof_id,aof_fileName from PaFi07(' + #partId + ');
sp_executesql #sqlCounter, N'#intCount int output, #intConst int, #intCount = ' + #intCount + ' output, #intConst = ' + #intConst + ' end')
If they are numeric values you would need to cast them:
... + cast(#intCount as varchar) + ...