Store the result of a Dynamic Query in a variable - sql

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;

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 .

How to store result of EXEC sys.sp_executesql

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

How to assigning value to parameter in dynamic query inside cursor

My problem is in the line with EXEC, all works except adding value to #counter.
If I execute something like below there is no problem:
EXEC('if exists(select * from '+ #table + ' where ' + #column + ' = ' + #someValue + ') print ''test''');
What to do to add value to the #counter? When I'm running below code I'm getting error:
Incorrect syntax near 0.
CREATE PROCEDURE testSP
AS
BEGIN
DECLARE testCursor CURSOR;
DECLARE #table NVARCHAR;
DECLARE #column NVARCHAR;
DECLARE #someValue NVARCHAR;
...
BEGIN
DECLARE testCursor2 CURSOR;
DECLARE #counter INT = 0;
...
BEGIN
DECLARE #result INT = 0;
EXEC( 'if exists(select * from '+ #table + ' where ' + #column + ' = ' + #someValue + ') set ' + #counter + '=1' );
IF (#counter > 0)
PRINT 'test';
...
END
...
END
END
go
You can use this.
CREATE PROCEDURE testSP
AS
BEGIN
DECLARE testCursor CURSOR;
DECLARE #table NVARCHAR;
DECLARE #column NVARCHAR;
DECLARE #someValue NVARCHAR;
...
BEGIN
DECLARE testCursor2 CURSOR;
DECLARE #counter INT = 0;
...
BEGIN
DECLARE #result INT = 0;
declare #sqlText nvarchar(max)= N'if exists(select * from '+ #table + ' where ' + #column + ' = ' + #someValue + ') SET #counter = 1'
DECLARE #ParmDefinition nvarchar(500) = N'#counter INT OUTPUT';
EXEC sp_executesql #sqlText, #ParmDefinition, #counter = #counter OUTPUT ;
if(#counter>0)
print 'test';
...
END
...
END
END

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 '

SQL Server - Cursor Error

I am declaring a dynamic cursor due to a nesting of the stored procedure based on a parent-child relationship of the data that can go multiple levels and vary daily when processed. The stored procedure works for the parent call, however the process of this procedure for child data causes a message stating that the "Cursor is not open." This message occurs on the Fetch which is immediately after checking to be sure the cursor is open.
DECLARE #OutCur CURSOR;
DECLARE #curName as NVARCHAR(MAX);
...
SET #curName = LEFT(replace(replace(CONVERT (time, GETDATE()),':',''),'.',''),8);
SET #sqlCommand = 'SELECT a.myfields FROM mytable a;
SET #sqlCommand = 'SET #cursor' + #curName + ' = CURSOR LOCAL FAST_FORWARD FOR ' + #sqlCommand + ' OPEN #cursor' + #curName + ';'
SET #curName = '#cursor' + #curName + ' cursor output';
EXEC sys.sp_executesql #sqlCommand,#curName,#OutCur output
IF CURSOR_STATUS('global','#OutCur')=-1
OPEN #OutCur;
FETCH NEXT FROM #OutCur INTO #name,#type
Thanks in advance for the input.
if you uncomment close+deallocate - script works fine:
GO
DECLARE #OutCur CURSOR;
DECLARE #curName as NVARCHAR(MAX), #sqlCommand nvarchar(max), #name varchar(100), #type varchar(100)
declare #i int = 0
while #i < 5
begin
SET #curName = LEFT(replace(replace(CONVERT (time, GETDATE()),':',''),'.',''),8);
SET #sqlCommand = 'SELECT ''111'' as name, ''cc'' as type; '
SET #sqlCommand = 'SET #cursor' + #curName + ' = CURSOR LOCAL FAST_FORWARD FOR ' + #sqlCommand + ' OPEN #cursor' + #curName + ';'
SET #curName = '#cursor' + #curName + ' cursor output';
EXEC sys.sp_executesql #sqlCommand,#curName,#OutCur output
FETCH NEXT FROM #OutCur INTO #name,#type
select #name, #type
--close #OutCur
--deallocate #OutCur
set #i += 1
end
GO