Click here to Skip to main content
15,886,806 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
My code is

SQL
declare @ColName varchar(20)
declare @sql nvarchar(1000)


set @ColName='Days1'

set @sql='update Table1 set'+' '+ @ColName+'=P'
print @sql
EXEC sp_executesql @sql


when I run this then out put comes

update Table1 set Days1=P
Msg 207, Level 16, State 1, Line 1
Invalid column name 'P'.
Posted

1 solution

You are missing quotes for the string update.
set @sql='update Table1 set'+' '+ @ColName+'=''P'''
 
Share this answer
 
Comments
Member 7909353 7-May-15 4:50am    
declare @ColName varchar(20)
declare @sql nvarchar(1000)
DECLARE @sitename nvarchar(30)
DECLARE @userId nvarchar(10)
DECLARE @cn nvarchar(70)
set @cn=(select ContractorName from Table1);
set @userid=1
set @ColName='Days1'
set @sql='update Table1 set'+' '+ @ColName+'=''P'''+' where UserId='+@userId
It is right
but when I concate

set @sql='update Table1 set'+' '+ @ColName+'=''P'''+' where UserId='+@userId+' and ContractorName='+@cn


print @sql
EXEC sp_executesql @sql

update Table1 set Days1='P' where UserId=1 and ContractorName=a
Msg 207, Level 16, State 1, Line 1
Invalid column name 'a'.
Abhinav S 7-May-15 4:55am    
Same problem. You need quotes outside strings.
Member 7909353 7-May-15 7:41am    
I have tried but no solution
Member 7909353 8-May-15 2:05am    
yes it is solved
set @sql='update Table1 set'+' '+ @ColName+'=''P'''+' where UserId='+@userId+' and ContractorName='+''''+@cn+''''

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900