【问题标题】:SQL Query : populating only null valueSQL 查询:仅填充空值
【发布时间】:2012-08-30 01:13:17
【问题描述】:

我正在尝试使用 SQL Server Management Studio 2008 运行以下查询。

update Schema.[ClientNew]  
set [Notes] = ([Notes]+ char(10)+(Select [Notes] from Schema.[clientOld]
where  office = 90  and ID = '123456789AM')) where  office = 90  and ID= '123456789' 

基本上试图将我的笔记字段中的所有数据从 clientOld 合并到 clientnew 中的 notes 字段。

这只是代码的一部分。

拆开时:

 Select [Notes] from Schema.[clientOld] where  office = 90  and ID = '123456789AM'

在备注字段中给我数据。

但是当我运行查询时,clientNew 表上只出现 {null} 值。

我的查询错了吗??还是在某处写空值?

请指教,

【问题讨论】:

  • ClientNew 在更新前在 Notes 中有空值?

标签: sql sql-server


【解决方案1】:

如果Schema.[ClientNew] 在字段[Notes] 中得到Null,则更新将不起作用。

这是因为您无法使用运算符Null 操作+

示例:

这样做:

select null + 'a'

结果将是null。 所以,如果你的表 ClientNew 有 NULL 值,这个

([Notes]+ char(10)+(Select [Notes] from Schema.[clientOld]
where  office = 90  and ID = '123456789AM'))

将返回 Null

尝试添加一个空字符串

(ISNULL([Notes], '') + char(10)+(Select [Notes] from Schema.[clientOld]
where  office = 90  and ID = '123456789AM'))

【讨论】:

  • 是的。空值是问题所在。我知道这很愚蠢。谢谢你:)
【解决方案2】:

一个NULL +任何东西总是等于NULL,你需要使用COALESCE来防止NULL:

UPDATE    [Schema].ClientNew
SET              Server = COALESCE([Schema].ClientNew, '') + COALESCE([Schema].clientOld, '')
FROM         [Schema].ClientNew INNER JOIN
                      [Schema].clientOld ON [Schema].clientOld.office = [Schema].ClientNew.office AND ID = [Schema].ClientNew.ID
WHERE     (office = 90) AND (ID = '123456789AM')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-08
    相关资源
    最近更新 更多