如何使下面的语法更有效,因为我必须为一条记录更新超过20个字段?
UPDATE TRANS SET A = @XA WHERE UNIQX = @XUNIQX AND STS_TRANS = 0 and A <> @XA
UPDATE TRANS SET B = @XB WHERE UNIQX = @XUNIQX AND STS_TRANS = 0 and B <> @XB
UPDATE TRANS SET C = @XC WHERE UNIQX = @XUNIQX AND STS_TRANS = 0 and C <> @XC
UPDATE TRANS SET D = @XD WHERE UNIQX = @XUNIQX AND STS_TRANS = 0 and D <> @XD
UPDATE TRANS SET E = @XE WHERE UNIQX = @XUNIQX AND STS_TRANS = 0 and E <> @XE
答案 0 :(得分:1)
你可以把它结合起来:
UPDATE TRANS
SET A = @XA
,B = @XB
,C = @XC
,D = @XD
,E = @XE
WHERE UNIQX = @XUNIQX
AND STS_TRANS = 0;
即使A与@XA不同,也会有A
- &gt; A
(同一性)。
请注意,如果A列可以为空,A <> @XA
可能会很棘手:what is “=null” and “ IS NULL”
答案 1 :(得分:1)
使用这样的循环和动态sql:
create table #temp (idx int identity, column_name varchar(max))
insert #temp
select column_name from INFORMATION_SCHEMA.columns
where table_name='trans' --and filter columns you want here
declare @XUNIQX varchar(max) --set value here
declare @itrerator int = 1
declare @columnname varchar(max)
while @itrerator<=(select max(idx) from #temp)
begin
select @columnname=column_name from #temp where idx=@iterator
exec ('UPDATE TRANS SET '+@columnname+' = @X'+@columnname+' WHERE UNIQX ='+ @XUNIQX+' AND STS_TRANS = 0 and '+@columnname+' <> @X'+@columnname+'')
set @iterator=@iterator+1
end