2

I have this select statement and what i am trying to accomplish is when AuditLog is null then set 'Enabled' but my issues is i am not sure how to handle it when it is not NULL, i want to be able to get the data from AuditLog into AuditLogEnabled when it is not null. I have tried adding an else, but have not been able to get it to work. can someone show me the correct way to write this.

select FirstName,AuditLog,
CASE WHEN AuditLog IS NULL THEN 'Enabled' END AS AuditLogEnabled
from UserDetail
where FirstName = 'test'
4

3 回答 3

3

我建议使用 COALESCE -

SELECT FirstName,AuditLog,COALESCE(AuditLog,'Enabled') AS AuditLogEnabled
FROM UserDetail
WHERE FirstName = 'test'

使用 COALESCE 的原因 - ISNULL 取决于第一个参数的数据类型。有时它会导致数据截断 - 例如 -

DECLARE @value VARCHAR(5)
SELECT 'Using COALESCE', COALESCE(@value, 'My String')
SELECT 'Using ISNULL', ISNULL(@value, 'My String')

结果 -

Using COALESCE  My String
Using ISNULL    My St

这可能是一个严重的问题。除非您确定数据类型及其长度,否则不要使用 ISNULL。

于 2013-10-09T22:44:35.083 回答
3

你可以用一个案例来做,但在这种简单的情况下,我更喜欢ISNULL()

select FirstName,AuditLog,ISNULL(AuditLog,'Enabled') AS AuditLogEnabled
from UserDetail
where FirstName = 'test'
于 2013-10-09T20:26:52.790 回答
1

只要 AuditLog 是一个字符串,那么这样的东西应该可以工作:

select FirstName,
CASE WHEN AuditLog IS NULL THEN 'Enabled' ELSE AuditLog END AS AuditLogEnabled
from UserDetail
where FirstName = 'test'
于 2013-10-09T20:25:14.883 回答