How to store result of EXEC sys.sp_executesql - sql

How can I store the result of exec into a variable?
Here's my attempt at storing the data in a variable:
DECLARE #oltp VARCHAR(50) SET #oltp = 'emp'
DECLARE #wh VARCHAR(25) SET #wh = '_wh'
DECLARE #DatabaseName SYSNAME = #oltp + #wh;
DECLARE #oltp_data_days NVARCHAR(500)
DECLARE #Params NVARCHAR(500)
DECLARE #vi int
SET #oltp_data_days = N'(SELECT datediff(DAY, MIN(business_date), GETDATE()) AS keep_days
FROM '+QUOTENAME(#DatabaseName)+'..sales
WHERE business_date > ''1/1/2000 00:00:00'')'
EXEC sp_executesql #oltp_data_days = #oltp_data_days
, #Params = N'#vi INT OUTPUT'
, #vi = #vi OUTPUT
I am getting results as Null.

Like this:
declare #sql nvarchar(max) = N'set #vi = (select 3 as keep_days)'
declare #vi int
exec sp_executesql #sql, N'#vi int output', #vi = #vi output
select #vi

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 .

Setting variable to its own value's value dynamically - Possible?

Using TSQL
Trying to set the #DynamicValue = 23 which is the parameter it is "equal" to in the below but can't figure it out.
DECLARE #DynamicValue VARCHAR(MAX) = '#PersonID';
DECLARE #PersonID INT = 23;
DECLARE #PlaceID INT = 48;
DECLARE #ThingID INT = 29;
DECLARE #nSQL NVARCHAR(MAX);
SET #nSQL = N'SELECT #Parameter2 = ' + CAST(#DynamicValue AS VARCHAR(MAX));
-- This is where the error is. If I used #PersonID here it would be fine but I want this to be dynamic
EXEC sp_executesql #nSQL,
N'#Parameter2 NVARCHAR(MAX) OUTPUT',
#Parameter2 = #DynamicValue OUTPUT;
SELECT #DynamicValue;
Any ideas? Different approaches?
You just have to pass all the parameters into the dynamic batch that performs the assignment.
Like this:
DECLARE #DynamicValue VARCHAR(MAX) = '#PersonID';
DECLARE #PersonID INT = 23;
DECLARE #PlaceID INT = 48;
DECLARE #ThingID INT = 29;
DECLARE #nSQL NVARCHAR(MAX);
SET #nSQL = N'set #Parameter2 = ' + CAST(#DynamicValue AS VARCHAR(MAX));
EXEC sp_executesql #nSQL,
N'#PersonID int, #PlaceID int, #ThingID int, #Parameter2 NVARCHAR(MAX) OUTPUT',
#PersonID = #PersonID, #PlaceID = #PlaceID, #ThingID = #ThingID, #Parameter2 = #DynamicValue OUTPUT;
SELECT #DynamicValue;
The only way I see:
DECLARE #DynamicValue VARCHAR(MAX) = '#PersonID';
DECLARE #PersonID INT = 23;
DECLARE #PlaceID INT = 48;
DECLARE #ThingID INT = 29;
SELECT #DynamicValue = CAST(CASE #DynamicValue
WHEN '#PersonID' THEN #PersonID
WHEN '#PlaceID' THEN #PlaceID
WHEN '#ThingID' THEN #ThingID END as VARCHAR(MAX))
SELECT #DynamicValue
EzLo's comment above that a variable declared outside of dynamic SQL can't be accessed made me rewrite your code in the following way, seems to work:
SET #nSQL = N'DECLARE #PersonID INT = ' + CAST(#PersonID as varchar)
+' DECLARE #PlaceID INT = ' + CAST(#PlaceID as varchar)
+' DECLARE #ThingID INT =' + CAST(#ThingID as varchar)
+' SELECT #Parameter2 = ' + CAST(#DynamicValue AS VARCHAR(MAX));
There is another way to do the same trick, but you still would have to list all your parameters:
DECLARE #DynamicValue VARCHAR(MAX) = '#PersonID';
DECLARE #PersonID INT = 23;
DECLARE #PlaceID INT = 48;
DECLARE #ThingID INT = 29;
DECLARE #DynamicValues TABLE (Parameter VARCHAR(MAX), Value INT)
INSERT INTO #DynamicValues VALUES
('#PersonID',#PersonID),
('#PlaceID',#PlaceID),
('#ThingID',#ThingID);
SELECT #DynamicValue = CAST(Value as VARCHAR(MAX))
FROM #DynamicValues WHERE Parameter = #DynamicValue
SELECT #DynamicValue

Get value of SQL Var conformed on varchar text

I have the next script example:
DECLARE #lCode INT
DECLARE #lText VARCHAR(400)
DECLARE #lConditionName VARCHAR(40)
DECLARE #Aux VARCHAR(400)
SET #lCode = 1234;
SET #lConditionName = 'Code'
SET #Aux = '#l' + #lConditionName
SET #lText = 'SELECT * FROM Table WHERE Code = ' + #Aux
PRINT #lText
The result is:
SELECT * FROM Table WHERE Code = #lCode
How can i obtein the value of #Aux Var like this?
SELECT * FROM Table WHERE Code = 1234
DECLARE #lCode INT
DECLARE #lText NVARCHAR(400)
DECLARE #lConditionName NVARCHAR(40)
DECLARE #Aux NVARCHAR(400)
SET #lCode = 1234;
SET #lConditionName = N'Code'
SET #Aux = N'#l' + #lConditionName
SET #lText = N'SELECT * FROM Table WHERE Code = ' + #Aux
PRINT #lText
EXEC sp_executesql #lText, N'#lcode INT', #lcode
You can try this :
DECLARE #lCode INT
DECLARE #lText NVARCHAR(400)
DECLARE #lConditionName NVARCHAR(40)
DECLARE #Aux NVARCHAR(400)
SET #lCode = 1234;
SET #lConditionName = N'Code'
SET #Aux = N'#l' + #lConditionName
SET #lText = N'SELECT * FROM Table WHERE Code = ' + #Aux
set #lText = N'Print ' + #Aux
print #lText
EXEC sp_executesql #lText, N'#lcode INT', #lcode
Output
Print #lCode
1234

Problems with output parameter

I have problem when I run this procedure it gives me back an error trying to parse 'ok' to int but I dont want result to be int.
DECLARE #result_var nvarchar(max)
DECLARE #ParmDefinition NVARCHAR(max)
EXECUTE Sp_executesql
#definition,
#ParmDefinition,
#result_var = #result_var output;
Code that is changing #result_var
SET #result_var = ''ok'';
DECLARE #cursor CURSOR,
#name VARCHAR(100)
SET #cursor = CURSOR FOR
SELECT [NAME]
FROM [iflvs08].mds.mdm.lv_budget_employee
OPEN #cursor
FETCH next FROM #cursor INTO #name
WHILE ##FETCH_STATUS = 0
BEGIN
IF RIGHT(#Name, 1) = '' ''
begin
IF (Len(#result_var) > 1)
SET #result_var = #result_var + '','' + #name
ELSE
SET #result_var = #name
END
FETCH next FROM #cursor INTO #name
END
Looks like that you declared but didn't set up #ParmDefinition variable.
It should be like this:
DECLARE #ParmDefinition NVARCHAR(max)
SET #ParmDefinition = N'#result_var nvarchar(max) OUTPUT';
EXECUTE Sp_executesql
#definition,
#ParmDefinition,
#result_var=#result_var output ;

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;