I spend lot of time to figure out, what is the error,
l have code like this.
DECLARE #GeofenceName nvarchar(50) = '';
DECLARE #sql AS NVARCHAR(MAX)
SET #sql = N'select * from GeofenceMaster where GeofenceName = GName'
EXEC sp_executesql #sql,N'GName nvarchar(50)',#GeofenceName
PRINT #sql
it throw a error like this.
Msg 102, Level 15, State 1, Line 1 Incorrect syntax near 'GName'.
select * from GeofenceMaster where GeofenceName = GName
anybody know which cause this problem?
UPDATE:
The original answer is incorrect. No parentheses should be required. See http://msdn.microsoft.com/en-us/library/ms188001(v=sql.105).aspx
New answer
Try
DECLARE #GeofenceName nvarchar(50) = '';
DECLARE #sql AS NVARCHAR(MAX)
set #sql = N'select * from GeofenceMaster where GeofenceName = #GName'
EXEC sp_executesql #sql,N'GName nvarchar(50)',#GName=#GeofenceName
I've amended the SQL itself, ... = GName becomes ... = #GName and the execution, ..., #GeofenceName becomes ..., #GName = #GeofenceName.
Original answer
You need to add some brackets.
Instead of
EXEC sp_executesql #sql,N'GName nvarchar(50)',#GeofenceName
Try
EXEC sp_executesql(#sql,N'GName nvarchar(50)',#GeofenceName)
the problem is in the variable "GName" (should have #, in this case would #GName), try with the following code, this works perfectly (for more info, see this LINK):
DECLARE #sql AS NVARCHAR(MAX)
declare #GName AS nvarchar(50) = ''
SET #sql = N'select * from GeofenceMaster where GeofenceName = ''' + #GName + ''''
EXEC sp_executesql #sql,N'#GName nvarchar(50)',GName
PRINT #sql
Related
I'm trying to concatenate the string with multiple variables and go for exec. Unfortunately I'm facing the conversion problem as:
Conversion failed when converting the varchar value 'Select #ExistingIds= CBSE_IX_J from ##tempPivot where EmployeeID=' to data type int.
My query is :
SET #ExecColumn = concat('Select #ExistingIds= '+#TSectionName +' from ##tempPivot where EmployeeID='+CAST(#TUserID as INT),'')
PRINT #ExecColumn
EXEC (#ExecColumn)
The "simple" answer is don't concatenate raw string values into your dynamic statement, and parametrise your code. This is a bit of guesswork, however, is far safer than the SQL Injection hole you have right now:
DECLARE #SQL nvarchar(MAX);
SET #SQL = N'SELECT #ExistingIDs = ' + QUOTENAME(#TSectionName) + NCHAR(13) + NCHAR(10)+
N'FROM ##tempPivot' + NCHAR(13) + NCHAR(10) +
N'WHERE EmployeeID = #TUserID;';
PRINT #SQL;
EXEC sp_executesql #SQL,
N'#TUserID int, #ExistingIds int OUTPUT', --guessed datatypes and that #ExistingIds is an OUTPUT
#TUserID = #TUserID,
#ExistingIds = ExistingIds OUTPUT;
Note: the fact that your variable is called #ExistingIDs implies you want to store multiple values in that variable. #ExistingIDs is a scalar value, it will only hold a scalar (single) value. If the query above returns multiple rows, only the value of from the last row will be returned. For example:
DECLARE #i int;
SELECT #i = I
FROM (VALUES(1),(2),(3),(4),(5),(6),(7),(8),(9))V(I)
ORDER BY I;
SELECT #i;
Notice that #i has the value 9, not '1,2,3,...,9'.
You would seem to want:
DECLARE #SQL nvarchar(MAX);
DECALRE #ExistingIds NVARCHAR(MAX);
SET #SQL = N'
SELECT #ExistingIDs = STRING_AGG(#TSectionName, '''')
FROM ##tempPivot
WHERE EmployeeID = #TUserID
';
-- Cannot have identifiers as parameters, so use `REPLACE()`
SET #SQL = REPLACE(#SQL, '#TSectionName', QUOTENAME(#TSectionName);
EXEC sp_executesql #SQL,
N'#TUserID int, #ExistingIds NVARCHAR(MAX) OUTPUT', --guessed datatypes and that #ExistingIds is an OUTPUT
#TUserID=#TUserID,
#ExistingIds=#ExistingIds OUTPUT;
In older versions of SQL Server, you need another approach for concatenating strings. For instance
SET #SQL = N'
SELECT #ExistingIDs = (SELECT #TSectionName
FROM ##tempPivot
WHERE EmployeeID = #TUserID
FOR XML PATH ('')
)
';
How do I create variables that are specified once and then used in queries later in a script? These variables may be used multiple times in a query, and in multiple queries in a script. I use #x as such a variable in the examples below.
What I want to do is something like:
Declare #Query nvarchar(1000)
Declare #x nvarchar(40)
Set #x = 'test'
Set #Query = 'Select [Name]
, ' + #x + ' as [TestCase]
From mytable'
Exec (#Query)
-- returns "Invalid column name 'test'"
Which returns the error mentioned above. I would like it to achieve the equivalent of:
Declare #Query nvarchar(1000)
Declare #x nvarchar(40)
Set #x = 'test'
Set #Query = 'Select [Name]
, ''test'' as [TestCase]
From mytable'
Exec (#Query)
-- Returns e.g.
-- Name TestCase
-- Alice Test
-- Bob Test
I also note that the following doesn't work and returns the same error as the first:
Declare #Query nvarchar(1000)
Declare #x nvarchar(40)
Set #x = 'test'
Set #Query = 'Select [Name]
, ' + 'test' + ' as [TestCase]
From mytable'
Exec (#Query)
-- returns "Invalid column name 'test'"
Based on the error and since I'm not trying to use the #x as a column name, but just as a variable, I assume I'm using an invalid implementation of a variable.
Since you're not trying to use a variable as a column name, you do not need to use dynamic SQL at all. (Which is a Good Thing(TM) since dynamic SQL should only be used with a great deal of caution due to it being a great attack surface.)
A simple:
declare #x nvarchar(40)
set #x = 'test'
select [Name], #x as TestCase
from mytable
will do.
That being said, if you have a use case for dynamic SQL (again the particular query in question here does not but perhaps an ad-hoc query is being passed in to the procedure), the thing to do would be to pass your variable as a parameter to the query via sp_executesql. This is akin to creating a stored procedure with parameters:
declare #x nvarchar(40)
declare #query nvarchar(1000)
set #x = 'test'
set #query = 'select [Name], #x as TestCase from mytable'
exec sp_executesql #query, N'#x nvarchar(1000)', #x
You were missing quotes. Thats it. Try below code.
Declare #Query nvarchar(1000)
Declare #x nvarchar(40)
Set #x = 'test'
Set #Query = 'Select [Name]
, ''' + #x + ''' as [TestCase]
From mytable'
Exec (#Query)
Declare #Query nvarchar(1000)
Declare #x nvarchar(40)
Set #x = 'test'
Set #Query = 'Select [Name],'++''''+#x+''''+ ' as [TestCase]
From mytable'
print #query
Output:
Select [Name],'test' as [TestCase]
From mytable
I am trying to store next value for the sequence into a variable and the statement is called in a dynamic sql as below.
DECLARE #Sequence VARCHAR(100) = 'IMEIIDLookUP'
DECLARE #NextVal INT
DECLARE #SQL NVARCHAR(4000)
SELECT #SQL = 'SELECT (NEXT VALUE FOR [dbo].' + QUOTENAME(#Sequence) + ')'
SELECT #NextVal = EXEC (#SQL)
SELECT #NextVal
The above query fails with error
Incorrect syntax near the keyword 'EXEC'.
What would be the correct syntax here? Having said that, I cannot avoid using dynamic sql.
Use sp_executesql:
DECLARE #Sequence VARCHAR(100) = 'IMEIIDLookUP';
DECLARE #NextVal INT;
DECLARE #SQL NVARCHAR(4000);
SELECT #SQL = 'SELECT #NextVal = (NEXT VALUE FOR [dbo].' + QUOTENAME(#Sequence) + ')';
exec sp_executesql #SQL, N'#NextVal int output', #NextVal = #NextVal output;
SELECT #NextVal;
I keep getting an error with the following stored procedure. I had it working correctly using EXEC, then I switched to sp_executesql and I haven't been able to get it to execute. I keep getting the following error: Incorrect syntax near '#numberOfItems'.
ALTER PROCEDURE dbo.FetchResourcesToProcess
(
#tableName nvarchar(MAX),
#numberOfItems int
)
AS
BEGIN
DECLARE #SQL nvarchar(MAX);
SET NOCOUNT ON;
SET #SQL = N'Select TOP #numberOfItems * from ' + #tableName + N' where Active = 1 AND BeingProcessed = 0'
EXEC sp_executesql #SQL, N'#numberOfItems int', #numberOfItems
END
Tablename is a string structured as follows: "[TABLENAME]".
Thanks
You probably need to place number of items into the string the same way you are the table name
SET #SQL = N'Select TOP ' + Convert(varchar(10),#numberOfItems) + ' * from ' + #tableName + N' where Active = 1 AND BeingProcessed = 0'
I think you can only use parameters for sp_executesql statement in positions where variables are allowed.
use master;
declare #numberOfItems int;
set #numberOfItems = 2;
Select TOP #numberOfItems * from dbo.spt_values
Incorrect syntax near '#numberOfItems'.
use master;
declare #table varchar(max);
set #table = 'dbo.spt_values';
Select * from #table
Must declare the table variable "#table".
use master;
declare #numberOfItems int;
set #numberOfItems = 2;
Select TOP(#numberOfItems) * from dbo.spt_values
(2 row(s) affected)
Solution 1 (parenthesis, recommended):
SET #SQL = N'Select TOP(#numberOfItems) * from ' + #tableName + N' where Active = 1 AND BeingProcessed = 0'
Solution 2 (concatenation, make sure to prevent SQL injection!):
SET #SQL = N'Select TOP '+cast(#numberOfItems as nvarchar(MAX))+' * from ' + #tableName + N' where Active = 1 AND BeingProcessed = 0'
EXEC sp_executesql #SQL
I'm playing around with t-sql and would like to be able to select into some variable.
Currently I just want to get a count(*) for every table in the database and print this.
When I try the following:
EXEC('SELECT COUNT(*) FROM '+ #table_name)
This gives the counts for all rows, now, I'd like to store the COUNT(*) into a variable. To achieve this i've declared. I've tried a few different approaches, amongst others this one:
EXEC('SELECT ' + #row_count +' = COUNT(*) FROM '+ #table_name)
Which yields an error (Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '='.).
Any idea how to correctly express this?
You'll have to use sp_executesql.
Check this article for more info.
There is a more efficient way to get the number of rows in a table, by looking at the database metadata. Here is an alternative solution:
declare #NumRows int;
select #NumRows = sum(rows)
from <database>.sys.partitions P join
<database>.sys.tables T
on T.[object_id] = P.[object_id]
where index_id IN (0,1) AND T.[type] = 'U' and t.name = '<table>'
You need to provide output variable from a query and specify that it is for output:
declare #table_name nvarchar(100)
declare #row_count int
declare #sql nvarchar(max)
set #table_name = 'YOUR TABLE NAME'
set #sql = N'SELECT #row_count = COUNT(*) FROM '+ #table_name
exec sp_executesql #sql, N'#row_count int output', #row_count = #row_count output
print #row_count
Variable has to be declared in the appropriate context. try
declare #table_name varchar(50)
set #table_name ='users'
EXEC('declare #rcnt int;SELECT #rcnt = COUNT(*) FROM '+ #table_name+';select #rcnt ')
Probably do like this:
declare #rowcount int
declare #table_name nvarchar(10)
declare #sql nvarchar(max);
set #table_name = N'test';
set #sql = N'SELECT COUNT(*) FROM '+#table_name;
execute sp_executesql #sql,N'#rowcount int output',#rowcount = #rowcount output;
select #rowcount;