我有这样的更新查询:
update
set
column1 = @col1,
column2 = @col2,
...
column10 = @col10
from table
where table.id=@col0
我只需更新某些列取决于用户的输入。将值传递给此查询时,如何跳过某些列?
答案 0 :(得分:2)
您可以在update语句中使用大小写。 希望这会有所帮助:
我们假设您的表格如下:
create table tblTest
(
ID int,
column1 varchar(10),
column2 varchar(10),
column3 varchar(10),
column4 varchar(10),
column5 varchar(10)
)
插入测试值:
Insert into tblTest (ID, Column1,Column2,Column3,Column4, Column5) values (1,'a','b','c','d','e')
设置变量以进行测试。
declare @ID int
declare @col1 varchar(10)
declare @col2 varchar(10)
declare @col3 varchar(10)
declare @col4 varchar(10)
declare @col5 varchar(10)
set @ID = 1
set @col1 = 'a'
set @col2 = ''
set @col3 = 'y'
set @col4 = 'd'
set @col5 = 'z'
update tblTest
set
column1 = case when LEN(@col1) > 0 then @col1 else column1 end,
column2 = case when LEN(@col2) > 0 then @col2 else column2 end ,
column3 = case when LEN(@col3) > 0 then @col3 else column3 end ,
column4 = case when LEN(@col4) > 0 then @col4 else column4 end ,
column5 = case when LEN(@col5) > 0 then @col5 else column5 end
where
ID = @ID
select * from tblTest
我在这里用SQL Fiddle创建了一个示例:http://sqlfiddle.com/#!3/e666d/6
答案 1 :(得分:0)
我建议你可以将它们作为case语句发送,所以如果你将@col1作为NULL或''传递那么你可以做
update
set
column1 = CASE WHEN ISNULL(@col1,'')='' THEN column1 ELSE @col1 END,,
column2 = CASE WHEN ISNULL(@col2,'')='' THEN column2 ELSE @col2 END,,
...
column10 = CASE WHEN ISNULL(@col10,'')='' THEN column10 ELSE @col10 END,
from table
where table.id=@col0
答案 2 :(得分:0)
只需使用IsNull()
:
update
set
column1 = IsNull(@col1,column1),
column2 = IsNull(@col2,column2),
...
column10 = IsNull(@col10,column10)
from table
where table.id=@col0
它会做什么,它会检查变量(@col1
,@col2
等)是否为NULL
,如果是,则将列更新为其当前值,否则更新为变量值。只要缺少变量为空,它就会起作用