如何使用变量在update语句中指定列名 [英] How do I use a variable to specify the column name in a update statement
本文介绍了如何使用变量在update语句中指定列名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的代码是
声明 @ColName varchar ( 20 )
声明 @sql nvarchar ( 1000 )
set @ColName = ' Days1'
set @sql = ' update Table1 set' + ' ' + @ ColName + ' = P'
print @ sql
EXEC sp_executesql @sql
当我运行这个然后输出来的时候
更新表1设置Days1 = P
消息207,级别16,状态1,行1
无效的列名称'P'。
解决方案
你缺少字符串更新的引号。
set @sql ='update Table1 set'+''+ @ColName +'=''P' ''
My code is
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'.
解决方案
You are missing quotes for the string update.
set @sql='update Table1 set'+' '+ @ColName+'=''P'''
这篇关于如何使用变量在update语句中指定列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文