Invalid column name when using sp_executesql - sql

When I try to execute a dynamic query inside a stored procedure I'm getting an error.
My code is:
DECLARE #Query nvarchar(max)
DECLARE #AllowanceBadge nvarchar(20)
DECLARE #AllowFieldName nvarchar(50)
DECLARE #Amount Decimal
SET #AllowanceBadge ='SIP0980'
SET #AllowFieldName ='xxxxx'
SET #Amount = 100
SET #Query = 'UPDATE tbl_PayrollTransaction SET '+ #AllowFieldName +' = '+convert(varchar,#Amount) + 'WHERE BadgeNumber = '+#AllowanceBadge
EXEC SP_EXECUTESQL #Query
I'm getting following error
Msg 207, Level 16, State 1, Line 1
Invalid column name 'SIP0980'.
Tell me where I'm wrong.
Thanks

Need quotes around the SIP0890
DECLARE #Query nvarchar(max)
DECLARE #AllowanceBadge nvarchar(20)
DECLARE #AllowFieldName nvarchar(50)
DECLARE #Amount Decimal
SET #AllowanceBadge ='SIP0980'
SET #AllowFieldName ='xxxxx'
SET #Amount = 100
SET #Query = 'UPDATE tbl_PayrollTransaction SET '+ #AllowFieldName +' = '+convert(varchar,#Amount) + 'WHERE BadgeNumber = '''+#AllowanceBadge+''''
EXEC SP_EXECUTESQL #Query

Related

Dynamic table name and variable name in query in SQL Server

I am trying to make a query that I can run from Python with dynamic table name and date. In the process of this, I have tried the following query in SSMS, but it is producing an error message. How can I use variables for table name and a date, and get the query to work?
DECLARE #table_name VARCHAR(50)='table_name';
DECLARE #valid_to datetime = getdate();
EXEC('UPDATE '+ #table_name + '
SET valid_flag = 0,
valid_to = '+ #valid_to +'
where valid_flag=1')
I get the following error message:
Msg 102, Level 15, State 1, Line 3
Incorrect syntax near '10'
Use sp_executesql and parameters:
DECLARE #table_name VARCHAR(50) = 'table_name';
DECLARE #valid_to datetime = getdate();
DECLARE #sql NVARCHAR(max) = N'
UPDATE '+ #table_name + N'
SET valid_flag = 0,
valid_to = #valid_to
WHERE valid_flag = 1
';
EXEC sp_executesql #sql, N'#valid_to datetime', #valid_to=#valid_to;
EDIT:
As recommended by Larnu a comment:
DECLARE #table_name sysname = 'table_name';
DECLARE #valid_to datetime = getdate();
DECLARE #sql NVARCHAR(max) = N'
UPDATE '+ QUOTENAME(#table_name) + N'
SET valid_flag = 0,
valid_to = #valid_to
WHERE valid_flag = 1
';
EXEC sp_executesql #sql, N'#valid_to datetime', #valid_to=#valid_to;

How to set a SQL variable with either EXEC or sp_executesql

I am attempting to build a query on the fly that will set a variable. How would I do this?
Here is what I have so far
DECLARE #SQL as NVARCHAR(500)
DECLARE #ParmDefinition NVARCHAR(500)
set #SQL = 'set #maxRowCount = (select count(*) from Test)'
SET #ParmDefinition = N'#maxRowCount int';
EXECUTE sp_executesql #SQL, #ParmDefinition
When I run this I get the following error
Msg 8178, Level 16, State 1, Line 1
The parameterized query '(#maxRowCount int)set #maxRowCount = (select count(*) from docto' expects the parameter '#maxRowCount', which was not supplied.
I am trying to get #maxRowCount to be set to the total row count of the Test table
This works, you need the 'OUTPUT' in the parameter definition and a place where the result goes to as well
DECLARE #SQL as NVARCHAR(500)
DECLARE #ParmDefinition NVARCHAR(500)
DECLARE #iRowCount INT
SET #SQL = 'set #maxRowCount = (select count(*) from Test)'
SET #ParmDefinition = N'#maxRowCount INT OUTPUT';
EXECUTE sp_executesql #SQL, #ParmDefinition, #maxRowCount = #iRowCount OUTPUT
PRINT 'rowcount is:' + CONVERT(VARCHAR,#iRowCount)

Can I use variable in condition statement as value with where condition that test that value

I have the following stored procedure:
ALTER proc [dbo].[insertperoll] #name nvarchar(50) , #snum int , #gnum int
as
DECLARE #value nvarchar(10)
SET #value = 's'+CONVERT(nvarchar(50),#snum)
DECLARE #sqlText nvarchar(1000);
DECLARE #sqlText2 nvarchar(1000);
DECLARE #sqlText3 nvarchar(1000);
declare #g nvarchar(50) = '''g1'''
SET #sqlText = N'SELECT ' + #value + N' FROM dbo.GrideBtable'
SET #sqlText2 = ' where Gnumber = '+#g --here is the problem it error invalid column name -- the #g is value from the table condition
set #sqlText3 = #sqlText+#sqlText2
Exec (#sqlText3) -- here how can i save the result of the exec into varibale
declare #sal nvarchar(50) = #sqlText3
insert employ (name,Snumber,Gnumber,Salary) values(#name,#snum,#gnum,#sal)
QUESTION: How to put in condition variable gets value from the table when i exec it it think that the #g is column but its not its a value from the table to test it so i display one value after the exec the other QUESTION is how to save the result from the exec in variable and then use that value
I'm using SQL Server 2008 (9.0 RTM)
This will be a stored procedure
Thanks in advance
Not sure why you would go through all the loops to insert into the table where you can have a simple insert query like ..
ALTER PROC dbo.[insertperoll] #name nvarchar(50) , #snum int , #gnum int
AS
insert employ (name, Snumber, Gnumber, Salary)
select #name
, #sum
, #gnum
, case when #snum = 1 then s1
when #snum = 2 then s2
when #snum = 3 then s3
when #snum = 4 then s4
end as Salary
from dbo.GrideBtable
where Gnumber = #gnum
If your intent is to have the proc retrieve a salary value from a column determined from the parameter snum and then make an insert into employ using the values passed as parameters and the salary retrieved I think you could refactor your procedure to this:
CREATE proc [dbo].[insertperoll] #name nvarchar(50) , #snum int , #gnum int AS
DECLARE #g NVARCHAR(50) = 'g1'
DECLARE #sql NVARCHAR(MAX);
SET #sql = N'INSERT employ (name,Snumber,Gnumber,Salary) '
SET #sql += N'SELECT ' + QUOTENAME(#name, '''')
SET #sql += N', ' + CAST(#snum AS NVARCHAR(50))
SET #sql += N', ' + CAST(#gnum AS NVARCHAR(50))
SET #sql += N', s' + CAST(#snum AS NVARCHAR(50))
SET #sql += N' FROM dbo.GrideBtable'
SET #sql += N' WHERE Gnumber = ' + QUOTENAME(#g, '''')
EXEC (#sql)
Of course you could add the #g variable to the procedure parameters instead of having it hard coded in the procedure and call it as:
EXEC insertperoll #name='john', #snum=10, #gnum=100, #g='g1'
Sample SQL Fiddle (with some assumptions made about table structure)
You could do this using sp_executesql instead of exec() since this will allow you to use parameters, you can use an output parameter to get the value from the query:
DECLARE #SQL NVARCHAR(MAX) = N'SELECT #val = ' + CONVERT(NVARCHAR(10),#snum) +
N' FROM dbo.GrideBtable WHERE Gnumber = #G1';
DECLARE #val INT; -- NOT SURE OF DATATYPE REQUIRED
EXECUTE sp_executesql #SQL, N'#G1 VARCHAR(20), #val INT OUT', 'G1', #val OUT;

SP_ExecuteSQL with Parameters doesn't like Contains clause

I've been tasked with modifying a stored procedure so that it goes from looking like this:
DECLARE #ID nvarchar(10)
SET #ID = '0000000001'
DECLARE #SQL nvarchar(200)
SET #SQL = 'SELECT AppN FROM Apps WHERE CONTAINS(ID, ''"*'' + #ID + ''*"'')'
EXECUTE SP_EXECUTESQL #SQL
to using the parameter list for SP_EXECUTESQL and not string concatenation. The issue is that the following doesn't appear to work:
DECLARE #CID nvarchar(10)
SET #CID = '0000000001'
DECLARE #ID2 nvarchar(14)
SET #ID2 = '"*' + #ID + '*"'
DECLARE #SQL nvarchar(200)
SET #SQL = 'SELECT AppN FROM Apps WHERE CONTAINS(ID, ID2)'
DECLARE #ParamDefinition NCHAR(300)
SET #ParamDefinition = '#ID2 nvarchar(10)'
EXECUTE SP_EXECUTESQL #SQL, #ParamDefinition, #ID2
For whatever reason, the first set of statements works fine. The second does not. I get the following error message: Syntax error near '"' in the full-text search condition '"*00000000'.
If I remove 4 characters from #ID the second set of statements also works. Clearly it has something to do with the length of either #ID or the column ID but I can't figure out what.
You define #ID2 as nvarchar(10) in your parameters for the dynamic SQL.
It's actually 14 characters, so you are cutting off the end of it.
This outputs the correct variable for me:
DECLARE #CID nvarchar(10)
SET #CID = '0000000001'
DECLARE #ID2 nvarchar(14)
SET #ID2 = '"*' + #CID + '*"'
DECLARE #SQL nvarchar(200)
SET #SQL = 'SELECT #ID2'
DECLARE #ParamDefinition NCHAR(300)
SET #ParamDefinition = '#ID2 nvarchar(14)'
EXECUTE SP_EXECUTESQL #SQL, #ParamDefinition, #ID2

Procedure error "Must declare the table"

I have a block code to create a procedure:
CREATE PROCEDURE GetTableinfomation
#table nvarchar(50),
#column nvarchar(50),
#valuedk nvarchar(50)
AS
BEGIN
SELECT *
FROM #table
WHERE #column = #valuedk
END
and I have an error.
Msg 1087, Level 15, State 2, Procedure GetTableinfomation, Line 7
Must declare the table variable "#tenbang".
Why?
You cannot use SQL parameters for table names and columns, only for variables.
You could get around this by using dynamic SQL:
DECLARE #SQL nvarchar(4000)
DECLARE #PARAMS nvarchar(4000)
SET #SQL = 'SELECT * FROM '
+ QUOTENAME(#table,'"') + ' WHERE '
+ QUOTENAME(#column,'"') + '= #param1'
SET #PARAMS = '#param1 nvarchar(50)'
EXEC sp_executesql #SQL, #PARAMS, #param1=#valuedk
See the documentation on sp_executesql for more information:
http://msdn.microsoft.com/en-us/library/ms188001.aspx