Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/258.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 更新sql中的某些列_C#_Sql Server_Tsql - Fatal编程技术网

C# 更新sql中的某些列

C# 更新sql中的某些列,c#,sql-server,tsql,C#,Sql Server,Tsql,我有一个更新查询,如下所示: update set column1 = @col1, column2 = @col2, ... column10 = @col10 from table where table.id=@col0 我只需要根据用户的输入更新某些列。在将值传递到此查询中时,如何跳过某些列?我建议您可以将它们作为case语句发送,因此如果将@col1传递为NULL或“”,则可以这样做 update set column1 = CASE WHEN ISNULL(@col1,'')=''

我有一个更新查询,如下所示:

update
set
column1 = @col1,
column2 = @col2,
...
column10 = @col10
from table
where table.id=@col0

我只需要根据用户的输入更新某些列。在将值传递到此查询中时,如何跳过某些列?

我建议您可以将它们作为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

您可以在update语句中使用case。 希望这有助于:

假设您的表格如下所示:

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创建了一个示例:

只需对其使用
IsNull()

update
set
column1 = IsNull(@col1,column1),
column2 = IsNull(@col2,column2),
...
column10 = IsNull(@col10,column10)
from table
where table.id=@col0

它将检查变量(
@col1
@col2
等)是否为
NULL
,如果是,则将列更新为当前值,否则更新为变量值。只要缺少的变量是空的,它就可以工作。

您的意思是有条件地跳过某些列吗?就像您有
@col1
@col3
值一样,更新将只更新这两列?这是在存储过程中还是在C#中直接表示,在哪里/如何生成和运行此查询?这些因素将决定答案。是,有条件地跳过某些列。这是直接在C#中使用的,但它在一个资源文件中。我不能使用c#有条件地连接sql字符串。