我有一个这样的更新查询:更新某些列在SQL
update
set
column1 = @col1,
column2 = @col2,
...
column10 = @col10
from table
where [email protected]
我只需要更新某些列取决于用户的输入。将值传递到此查询时如何跳过某些列?
我有一个这样的更新查询:更新某些列在SQL
update
set
column1 = @col1,
column2 = @col2,
...
column10 = @col10
from table
where [email protected]
我只需要更新某些列取决于用户的输入。将值传递到此查询时如何跳过某些列?
我建议你可以把他们作为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 [email protected]
您可以在更新语句中使用的情况。 希望这有助于:
让我们假设你的表如下:
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小提琴这里的样本:http://sqlfiddle.com/#!3/e666d/6
只是用IsNull()
它:
update
set
column1 = IsNull(@col1,column1),
column2 = IsNull(@col2,column2),
...
column10 = IsNull(@col10,column10)
from table
where [email protected]
会是什么时,它会检查变量(@col1
, @col2
等)是NULL
,如果是这样,更新列的当前值,否则更新到变量的值。只要缺失变量为空值,它就会工作
是否有条件地跳过某些列?就像如果你有'@ col1'和'@ col3'值,更新只会更新这两列?这是在存储过程还是直接在C#中 - 这意味着,在何处/如何生成并运行此查询?这些因素将决定答案。 –
是有条件地跳过某些列。这在C#中直接使用,但它在一个资源文件中。我不能使用c#来有条件地连接sql字符串。 – Meidi