简体   繁体   English

在所有表列中更新不为null

[英]Update Not null in all table columns

I want to update null to not null columns with one query for all columns of table. 我想用一个查询表的所有列将null列更新为非null列。 Like if I have column "int" which have null then it will 0 and "string" will "". 就像如果我的列“ int”具有null,则它将为0,“ string”将为“”。

Is it possible with a single SQL query? 一个SQL查询可能吗?

I don't want to execute separate queries for update and set not null because I have many tables and have many columns. 我不想为更新执行单独的查询,并且不设置为null,因为我有很多表并且有很多列。

Thanks in advance. 提前致谢。

There's no magic shortcut - you will need to use an UPDATE command for each table, and you need to list each column you want to update separately: 没有神奇的捷径 -您将需要为每个表使用UPDATE命令,并且需要列出要单独更新的每个列:

UPDATE dbo.YourTable
SET IntColumn = ISNULL(IntColumn, 0),
    VarCharColumn = ISNULL(VarCharColumn, "")

and so on.... 等等....

there is no real shortcut from sql server to do this, but u can use dirty way and u need be careful when using it. sql server并没有真正的快捷方式来执行此操作,但是您可以使用肮脏的方式,使用时请务必小心。

declare @tableName varchar(200) = 'TABEL1'
declare @query1 varchar(max) = ''

select @query1 = @query1 + (case when @query1 = '' then '' else ', ' end) 
    + a.name +' = isnull('+a.name+','+  (case when a.system_type_id in (56) then '0' when a.system_type_id in (167) then '''''' else a.name  END) +')'
from sys.all_columns a
inner join sys.all_objects b
    on a.object_id = b.object_id
where b.name = @tableName

set @query1 = ' UPDATE '+ @tableName +' SET '+ @query1

execute(@query1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM