How to set value to declared variable in SQL Server.
DECLARE #V_SEQUENCE INT, #V_SEQUENCENAME NVARCHAR(MAX);
SET #V_SEQUENCENAME = 'dbo.MYSEQ';
EXEC('SELECT #V_SEQUENCE = NEXT VALUE FOR ' + #V_SEQUENCENAME)
SELECT #V_SEQUENCE
Here i am getting an error:
Must declare the scalar variable "#V_SEQUENCE"'
Please tell me how to get result of #V_SEQUENCE.
You want to pass a value out of the execute. I recommend that you use sp_executesql:
DECLARE #V_SEQUENCE INT, #V_SEQUENCENAME NVARCHAR(MAX), #SQL NVARCHAR(MAX);
SET #V_SEQUENCENAME = 'dbo.MYSEQ';
SELECT #SQL = 'SELECT #V_SEQUENCE = NEXT VALUE FOR ' + #V_SEQUENCENAME;
EXEC sp_executesql #SQL, N'#V_SEQUENCE INT OUTPUT', #V_SEQUENCE = #V_SEQUENCE OUTPUT;
SELECT #V_SEQUENCE;
Related
I have a query like this:
DECLARE #TaskId UNIQUEIDENTIFIER
DECLARE #TaskName VARCHAR(255) = 'MasterSet'
DECLARE #sql NVARCHAR(MAX)
DECLARE #StartingDateTask DATETIME2 = (SELECT TOP 1 [Date]
FROM [TaskStatusAudit]
WHERE [TaskId] = 'A1FDFC16-904D-4560-B19D-5E7D4FEB1C2B'
AND [TaskStatusName] = 'IN-PROGRESS')
DECLARE #EndingDateTask DATETIME2 = (SELECT TOP 1 [Date]
FROM [TaskStatusAudit]
WHERE [TaskId] = 'A1FDFC16-904D-4560-B19D-5E7D4FEB1C2B'
AND [TaskStatusName] = 'COMPLETED')
SET #sql = N'SELECT dbo.TotalMinuteRange(#StartingDateTask,#EndingDateTask) as ' + quotename(#TaskName) + N''
EXEC sp_executesql #sql
Problem is when I execute it I get this error:
Must declare the scalar variable "#StartingDateTask".
Any ideas why I getting that if I declare my variable correctly? Regards
When executing sp_executesql you need to declare and pass the variables to sp_executesql something like..
SET #sql = N'SELECT dbo.TotalMinuteRange(#StartingDateTask,#EndingDateTask) as '
+ quotename(#TaskName) + N''
exec sp_executesql #sql
, N'#StartingDateTask DATETIME2 , #EndingDateTask DATETIME2'
, #StartingDateTask
, #EndingDateTask
Second parameter is the variable declaration parameter followed by the actual variables separately.
You can also do like taking a parameters variable and assign it.
declare #params nvarchar(100)
set #params='#StartingDateTask DATETIME2,#EndingDateTask DATETIME2'
SET #sql = N'SELECT dbo.TotalMinuteRange(#StartingDateTask,#EndingDateTask) as '
+ quotename(#TaskName) + N''
exec sp_executesql #sql
, #params
, #StartingDateTask
, #EndingDateTask
I am creating a stored procedure with a cursor and I need to store the quantity of a column into a variable.
SQL says that it cannot convert nvarchar into int
I have tried to use CONVERT, CAST and EXEC but couldn't make it work.
How can I solve this ?
DECLARE #FieldName nvarchar(255);
DECLARE #RequestCode Nvarchar(50);
DECLARE #ReqSQLQuantity nvarchar(max);
DECLARE #Quantity int;
Select #ReqSQLQuantity = concat('select count(*) From (select distinct [', #FieldName , '] from [report_' , #RequestCode , ']) as number')
Set #Quantity = (#ReqSQLQuantity)
Select #Quantity
Another a bit safer option would be to use sp_executesql stored procedure something like this....
DECLARE #FieldName nvarchar(255);
DECLARE #RequestCode Nvarchar(50);
DECLARE #ReqSQLQuantity nvarchar(max);
DECLARE #Quantity int, #tableName SYSNAME;
SET #tableName = N'report_' + #RequestCode
Select #ReqSQLQuantity = N' select #Quantity = count(*) '
+ N' From (select distinct ' + QUOTENAME(#FieldName)
+ N' from ' + QUOTENAME(#tableName) + N' ) as number'
Exec sp_executesql #ReqSQLQuantity
,N'#Quantity INT OUTPUT'
,#Quantity OUTPUT
Select #Quantity
Set #Quantite = (#ReqSQLQuantite)
This is not an evaluation, is an implicit conversion. From NVARCHAR to INT, and you are trying to convert a SQL query text into an INT, hence the error.
Also, you are assuming that results are the same as return values and can be assigned to variables. This is incorrect, SQL execution results are sent to the client. To capture a result, you must use a SELECT assign: SELECT #value =.... Trying to run #variable = EXEC(...) is not the same thing. Think at SELECT results the same way as a print in an app: a print sends some text to the console. If you run some pseudo-code like x = print('foo') then 'foo' was sent to the console, and x contains the value returned by print (whatever that is). Same with this pseudo-SQL, #x = EXEC('SELECT foo') will send foo to the client, and #x will some numeric value which is the value returned by EXEC (in a correct example one would have to use explicit RETURN statement to set it).
Overall, the code as posted has absolutely no need for capturing the value and returning it, it can simply execute the dynamic SQL and let the result be returned to client:
SET #sql = concat(N'SELECT count(*) FROM (SELECT ... FROM ...)');
exec sp_executesql #sql;
I am trying to get a dynamic count to print out but it is telling me
#totalCAUUpdates needs a scalar value. Any thoughts?
declare #totalCAUUpdates as int = 0;
declare #realTableName as varchar(100) = '[_TEMP_SubscriptionTransactionsForMosoPay09022014]'
declare #updateSQL as varchar(1000) = 'select #totalCAUUpdates = count(*) from ' + #realTableName + ' where len(accountNumberUpdated) > 0 OR len(accountAccessoryUpdated) > 0;';
raiserror (#updateSQL, 0,1) with nowait;
EXEC (#updateSQL);
DECLARE #totalCAUUpdates INT= 0;
DECLARE #updateSQL NVARCHAR(MAX);
DECLARE #realTableName SYSNAME;
SET #realTableName = '_TEMP_SubscriptionTransactionsForMosoPay09022014';
SET #updateSQL = N'select #totalCAUUpdates = count(*) from ' + QUOTENAME(#realTableName)
+ N' where len(accountNumberUpdated) > 0 OR len(accountAccessoryUpdated) > 0;';
EXECUTE sp_executesql #updateSQL
,N'#totalCAUUpdates INT OUTPUT'
,#totalCAUUpdates OUTPUT
your batch is being executed inside another session, where #totalCAUUpdates is not visible.
You need to use sp_ExecuteSQL instead.. This proc allows you to pass in values declared in the calling session and use them with a declared variable in the called session
I'm trying to verify a job number exists on a linked server and get back a variable (#JobExists) indicating whether it does or not (1 for yes, 0 for no).
To do this I'm trying to use OPENQUERY along with sp_executesql as I have to pass in a parameter for the job number. I've tried the code below but get the error 'Procedure expects parameter '#statement' of type 'ntext/nchar/nvarchar'. For testing purposes I've declared and set the variable #JobNumber.
DECLARE #JobNumber as varchar(50)
SET #JobNumber = '2112111'
DECLARE #JobExists as BIT
DECLARE #JobCount as int
DECLARE #ParmDefinition as varchar(100)
DECLARE #sql as varchar(500)
SET #JobExists = 0
SET #ParmDefinition = N'#Result int output'
SET #sql = 'SELECT #Result = SELECT COUNT(*) FROM OPENQUERY(MYLINKEDSVR,''SELECT JOB_NUMBER FROM PROD.tbl1 WHERE JOB_NUMBER = ''''' + UPPER(RTRIM(LTRIM(#JobNumber))) + ''''''')'
exec sp_executesql #sql, #ParmDefinition, #Result = #JobCount output
IF #JobCount > 0
SET #JobExists = 1
SELECT #JobExists
I've read up sp_executesql here: http://technet.microsoft.com/en-us/library/ms188001.aspx
I've also done various searches but haven't come across any answers that work for me.
Is there something I'm missing?
The error message is clear: you must declare #sql as nvarchar and not as varchar.
The same for #ParamDefinition:
DECLARE #ParmDefinition as nvarchar(100)
DECLARE #sql as nvarchar(500)
I need to get data from a table in a database who's database name will be determined as a variable during a trigger. I then, knowing this variable need to get a seqno from a table in the determined database for a item which was also determined as a variable during a trigger.
I am trying this route as I assume I need to build the SQL statement before I set it to a variable.
This is not working and I need to know the best way on how I can do this:
DECLARE #SU_SEQNO INTEGER, #SU_NAME VARCHAR(50), #SU_OWNER VARCHAR(15), #SUD_SEQNO INTEGER, #SQL NVARCHAR(500)
SET #SU_OWNER = 'XXX'
SET #SU_NAME = '1ABC234'
SET #SQL ='SELECT #SUD_SEQNO=SEQNO FROM ' + (#SU_OWNER) + '.SU_MAIN
WHERE UNITNAME= ' + #SU_NAME
SET #SUD_SEQNO = (EXECUTE (#SQL))
Thanks alot for any help with this
From: Get result from dynamic SQL in stored procedure
SET #SQL = N'SELECT DISTINCT #FiscalYear = FiscalYear FROM ' + #DataSource;
EXEC sp_executesql #SQL, N'#FiscalYear INT OUTPUT', #FiscalYear OUTPUT;
PRINT #FiscalYear;
I'd re-engineer to use the sp_executesql method as shown above. That should do the trick.
I have amended the code, and it works
declare #su_owner varchar(15) = 'DBTEST'
declare #SU_SEQNO INTEGER=1, #SUD_SEQNO INTEGER=0, #SQL NVARCHAR(500)
DECLARE #ParmDefinition NVARCHAR(500), #SU_NAME_INPUT VARCHAR(50)='SU123'
SET #SU_NAME_INPUT = (SELECT UNITNAME FROM SU_MAIN WHERE SEQNO=#SU_SEQNO)
SET #SU_NAME = (SELECT UNITNAME FROM SU_MAIN WHERE SEQNO=#SU_SEQNO)
SET #SQL = N'SELECT #sud_seqnoOUT=MAX(SEQNO) FROM ' + quotename(#su_owner) + '.[dbo].[SU_MAIN] WHERE UNITNAME]=#SU_NAME_INPUT' ;
SET #ParmDefinition = N'#SU_NAME_INPUT VARCHAR(50),#sud_seqnoOUT INT OUTPUT'
EXEC sp_executesql #SQL,#ParmDefinition,#SU_NAME_INPUT = #SU_NAME,
#sud_seqnoOUT = #SUD_SEQNO OUTPUT