如果找不到行,则返回一个值SQL
这是我的简单查询。 如果我查询不存在的logging,那么我将不会返回任何内容。 我宁愿在这种情况下返回false(0)。 寻找简单的方法来解决没有logging。
SELECT CASE WHEN S.Id IS NOT NULL AND S.Status = 1 AND (S.WebUserId = @WebUserId OR S.AllowUploads = 1) THEN 1 ELSE 0 END AS [Value] FROM Sites S WHERE S.Id = @SiteId
SELECT CASE WHEN COUNT(1) > 0 THEN 1 ELSE 0 END AS [Value] FROM Sites S WHERE S.Id = @SiteId and S.Status = 1 AND (S.WebUserId = @WebUserId OR S.AllowUploads = 1)
这与Adam Robinson类似,但使用ISNULL而不是COUNT。
SELECT ISNULL( (SELECT 1 FROM Sites S WHERE S.Id = @SiteId and S.Status = 1 AND (S.WebUserId = @WebUserId OR S.AllowUploads = 1)), 0)
这可能是一匹死马,另一种返回1行的方式是当UNION不存在行时UNION另一个查询,并在表中不存在时显示结果。
SELECT S.Status, COUNT(s.id) AS StatusCount FROM Sites S WHERE S.Id = @SiteId GROUP BY s.Status UNION ALL --UNION BACK ON TABLE WITH NOT EXISTS SELECT 'N/A' AS Status, 0 AS StatusCount WHERE NOT EXISTS (SELECT 1 FROM Sites S WHERE S.Id = @SiteId )
就像是:
if exists (select top 1 * from Sites S where S.Id IS NOT NULL AND S.Status = 1 AND (S.WebUserId = @WebUserId OR S.AllowUploads = 1)) select 1 else select 0
我在这里读到所有的答案,花了一些时间来弄清楚发生了什么事情。 以下是基于“Moe Sisko”的回答和一些相关的研究
如果你的SQL查询没有返回任何数据,那么就不会有一个空值的字段,所以ISNULL和COALESCE都不会按你所希望的那样工作。 通过使用子查询,顶级查询将获得一个空值的字段,并且ISNULL和COALESCE都可以按照您希望的/期望的方式工作。
我的查询
select isnull( (select ASSIGNMENTM1.NAME from dbo.ASSIGNMENTM1 where ASSIGNMENTM1.NAME = ?) , 'Nothing Found') as 'ASSIGNMENTM1.NAME'
我的查询与评论
select isnull( --sub query either returns a value or returns nothing (no value) (select ASSIGNMENTM1.NAME from dbo.ASSIGNMENTM1 where ASSIGNMENTM1.NAME = ?) --If there is a value it is displayed --If no value, it is perceived as a field with a null value, --so the isnull function can give the desired results , 'Nothing Found') as 'ASSIGNMENTM1.NAME'
没有logging匹配意味着没有logging返回。 如果没有findlogging,那么没有地方为“0”值。 你可以创build一个疯狂的UNION查询来做你想做的事情,但是只要检查结果集中logging的数量就可以了。
你只需要用一个左连接replaceWHERE:
SELECT CASE WHEN S.Id IS NOT NULL AND S.Status = 1 AND ...) THEN 1 ELSE 0 END AS [Value] FROM (SELECT @SiteId AS Id) R LEFT JOIN Sites S ON S.Id = R.Id
该解决scheme允许您为每个列还返回默认值,例如:
SELECT CASE WHEN S.Id IS NULL THEN 0 ELSE S.Col1 END AS Col1, S.Col2, ISNULL(S.Col3, 0) AS Col3 FROM (SELECT @Id AS Id) R LEFT JOIN Sites S ON S.Id = R.Id AND S.Status = 1 AND ...
怎么样WITH TIES?
SELECT TOP 1 WITH TIES tbl1.* FROM (SELECT CASE WHEN S.Id IS NOT NULL AND S.Status = 1 AND (S.WebUserId = @WebUserId OR S.AllowUploads = 1) THEN 1 ELSE 0 AS [Value] FROM Sites S WHERE S.Id = @SiteId) as tbl1 ORDER BY tbl1.[Value]
这可能是一种方法。
SELECT TOP 1 [Column Name] FROM (SELECT [Column Name] FROM [table] WHERE [conditions] UNION ALL SELECT 0 )A ORDER BY [Column Name] DESC