Sql 为一行选择多个为空的列

Sql 为一行选择多个为空的列,sql,sql-server,Sql,Sql Server,我有1个id列和3个int列。 数据是以这种方式插入的 insert into table (col1, col2) values (1,1) insert into table (col2, col3) values (1,1) insert into table (col1, col3) values (1,1) insert into table (col1) values (1) 那么, 第1行第3列为空 第2行第1列为空, 第3行第2列为空。 第4行、第2列和第3列为空 我想

我有1个id列和3个int列。 数据是以这种方式插入的

insert into table (col1, col2) values (1,1) 

insert into table (col2, col3) values (1,1)

insert into table (col1, col3) values (1,1)

insert into table (col1) values (1)
那么, 第1行第3列为空 第2行第1列为空, 第3行第2列为空。 第4行、第2列和第3列为空

我想用0替换空值。我该怎么做


注意:我不知道哪些列是空的,因此我不能使用
ISNULL(colname,0)
当您想用其他内容替换可能为空的列时,请使用

大概是这样的:

SELECT ISNULL(COALESCE(Col1, Col2, Col3),0) FROM Table

如果要用其他内容替换可能为空的列,请使用

大概是这样的:

SELECT ISNULL(COALESCE(Col1, Col2, Col3),0) FROM Table
如果col1、2或3中的值不为null,则将用相同的值替换,否则如果为null,则将用0替换


如果col1、2或3中的值不为null,则将替换为相同的值,否则如果为null,则将替换为0。

如果要更新表,使
null
变为
0
,请使用
合并()


coalesce()
是ANSI标准函数,用于将
NULL
值替换为其他值。

如果要更新表,使
NULL
变为
0
,请使用
coalesce()


coalesce()
是ANSI标准函数,用于将
NULL
值替换为其他值。

我接受Gordon的,但最后我还是这样做了,因为我的列数可以更改,我希望它特定于某些行

CREATE PROCEDURE [setNullToZero]
    @rowSID VARCHAR(60) = 'A'
AS
BEGIN
declare @column_name as varchar(100)
declare col cursor for
SELECT column_name
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'dlgroups' 
ORDER BY ordinal_position;


open col;
fetch next from col into @column_name;
while @@FETCH_STATUS =0
begin
if (@column_name != 'id')
    exec('Update dlgroups set '+ @column_name +'=ISNULL('+@column_name+',0) WHERE sid='''+@rowSID+'''')

fetch next from col into @column_name
end
close col
deallocate col
END
GO

我会接受Gordon的,但最后我还是这么做了,因为我的列数可以改变,我希望它特定于某些行

CREATE PROCEDURE [setNullToZero]
    @rowSID VARCHAR(60) = 'A'
AS
BEGIN
declare @column_name as varchar(100)
declare col cursor for
SELECT column_name
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'dlgroups' 
ORDER BY ordinal_position;


open col;
fetch next from col into @column_name;
while @@FETCH_STATUS =0
begin
if (@column_name != 'id')
    exec('Update dlgroups set '+ @column_name +'=ISNULL('+@column_name+',0) WHERE sid='''+@rowSID+'''')

fetch next from col into @column_name
end
close col
deallocate col
END
GO

如果希望在默认情况下将
0
插入到列中,可以更改该表并将
default CONSTRAINT
设置为所需的列

ALTER TABLE myTable ADD DEFAULT(0) FOR Col1
无需更新声明


无论如何,您需要使用update语句更新现有记录。

如果您想在默认情况下将
0
插入列,您可以更改该表并将
默认约束设置为所需列

ALTER TABLE myTable ADD DEFAULT(0) FOR Col1
无需更新声明


无论如何,您需要使用update语句更新现有记录。

所以我对所有列执行for循环?@Splunk,我相信您的上一个语句可以在不使用ISNULL的情况下编写,即从表中选择COALESCE(Col1,Col2,Col3,0)以便我对所有列执行for循环?@Splunk,我相信您的上一个语句可以在没有ISNULL的情况下编写,即从表中选择COALESCE(Col1、Col2、Col3、0)在每列上使用
ISNULL
。有什么问题吗?所以我在所有的专栏中做了一个for循环?看看下面DeanOC或Gordon给出的答案。没有for循环,您只需对要更新的每一列执行
ISNULL
COALESCE
。对每一列使用
ISNULL
。有什么问题吗?所以我在所有的专栏中做了一个for循环?看看下面DeanOC或Gordon给出的答案。没有for循环,您只需对每个要更新的列执行
ISNULL
COALESCE