日期:2014-05-18  浏览次数:20471 次

MSSQL Update中使用变量
SQL code


declare @Row nvarchar(255)
declare @i int
select @i=COUNT(*)from SRV_Row
while(@i>0)
begin
select @Row=name from SRV_Row where SRV_RowID=@i
update SRV_SUB set @Row='yes'
where
SRV_PART_NO in (select distinct w.SRV_PART_NO from SRV_SUB s inner join ['WINDOWS 7 32$'] w on s.SRV_PART_NO=w.SRV_PART_NO where SUB_PH_NUMBER_AND_DESCRIPTION=@Row)
select @Row
set @i=@i-1
end

在这里,我在update的使用,使用了set与@row变量,我的本意是将列名为@row的列的值改为yes.但是在这里,则变成了每循环一次,将@row的值变成了yes.
求解决方法



------解决方案--------------------
exec('update SRV_SUB set'+ @Row_'='yes''
------解决方案--------------------
exec('update SRV_SUB set'+ @Row_+'='+quotename('yes',''''))
------解决方案--------------------
用动态执行函数exec()
SQL code
declare @Row nvarchar(255)
declare @sql text(8000)
declare @i int
select @i=COUNT(*)from SRV_Row
while(@i>0)
begin
select @Row=name from SRV_Row where SRV_RowID=@i
@sql ='update SRV_SUB set @Row='yes'
where
SRV_PART_NO in (select distinct w.SRV_PART_NO from SRV_SUB s inner join ['WINDOWS 7 32$'] w on s.SRV_PART_NO=w.SRV_PART_NO where SUB_PH_NUMBER_AND_DESCRIPTION=@Row)'
exec(@sql)
select @Row
set @i=@i-1
end

------解决方案--------------------
设置一个字符串变量,拼接SQL执行语句,然后动态执行,exec OR sp_executesql
------解决方案--------------------
SQL code
declare @Row nvarchar(255)
declare @sql text(8000)
declare @i int
select @i=COUNT(*)from SRV_Row
while(@i>0)
begin
select @Row=name from SRV_Row where SRV_RowID=@i
@sql ='update SRV_SUB set'+ @Row +' ='yes'
where
SRV_PART_NO in (select distinct w.SRV_PART_NO from SRV_SUB s inner join ['WINDOWS 7 32$'] w on s.SRV_PART_NO=w.SRV_PART_NO where SUB_PH_NUMBER_AND_DESCRIPTION=@Row)'
exec(@sql)
select @Row
set @i=@i-1
end

------解决方案--------------------
SQL code
declare @Row nvarchar(255)
declare @sql text(8000)
declare @i int
select @i=COUNT(*)from SRV_Row
while(@i>0)
begin
select @Row=name from SRV_Row where SRV_RowID=@i
@sql ='update SRV_SUB set'+ @Row +' =''yes''
where
SRV_PART_NO in (select distinct w.SRV_PART_NO from SRV_SUB s inner join [''WINDOWS 7 32$''] w on s.SRV_PART_NO=w.SRV_PART_NO where SUB_PH_NUMBER_AND_DESCRIPTION=@Row)'
exec(@sql)
select @Row
set @i=@i-1
end

------解决方案--------------------
SQL code

exec('update SRV_SUB set'+ @Row+'='+quotename('yes','''')+
'where
SRV_PART_NO in (select distinct w.SRV_PART_NO from SRV_SUB s 
inner join ['+quotename('WINDOWS 7 32$','''')+'] w on s.SRV_PART_NO=w.SRV_PART_NO where SUB_PH_NUMBER_AND_DESCRIPTION='+@Row+')'

------解决方案--------------------
SQL code

'update SRV_SUB set '+ @Row+'='+quotename('yes','''')+
' where '+'
SRV_PART_NO in (select distinct w.SRV_PART_NO from SRV_SUB s 
inner join ['+quotename('WINDOWS 7 32$','''')+'] w on s.SRV_PART_NO=w.SRV_PART_NO 
where SUB_PH_NUMBER_AND_DESCRIPTION='+@Row+')'