0

编写了一个 StackExchange DataExplorer 查询来按 User.Id 列出所有评论 该查询有效并返回Ids ofquestionsanswers。我不明白为什么answers第二列是空的。

DECLARE @UserId int = ##UserId##

Select p.Id
   , '<a href=https://stackoverflow.com/questions/' 
          + Cast(p.Id as varchar(20)) + '>'           
          + Cast(p.Id as varchar(20)) 
          + ' - ' + p.Title + '</a>'
   , c.Text
      FROM Users u            
      Join Comments c ON c.UserId = @UserId
      JOIN Posts p ON p.Id = c.PostId
      where u.Id = @UserId AND p.Id IS NOT NULL

即使假设该p.Title列为 NULL,该列p.Id也不是 NULL,因此我希望这部分

'<a href=https://stackoverflow.com/questions/' 
              + Cast(p.Id as varchar(20)) + '>'           
              + Cast(p.Id as varchar(20)) 
              + ' - ' + p.Title + '</a>'

会根据这个问题返回一些东西。但是第二列完全是空的。

为什么会这样?

4

1 回答 1

1

即使假设列 p.Title 为 NULL

它是那些行。

p.Id 列不为 NULL,因此我希望 [结果不为空]

没有。如果您NULL使用运算符与 SQL Server 中的任何内容连接,+那么您最终会得到NULLexcept if concat_null_yields_nullis OFF

您可以改用该CONCAT功能。这也节省了CAST

DECLARE @UserId INT = ##UserId##

SELECT p.Id,
       CONCAT('<a href=http://stackoverflow.com/questions/', 
              p.Id, 
              '>',
              p.Id, 
              ' - ',
              p.Title COLLATE SQL_Latin1_General_CP1_CI_AS, 
              '</a>'),
       c.Text
FROM   Users u
       JOIN Comments c
         ON c.UserId = @UserId
       JOIN Posts p
         ON p.Id = c.PostId
WHERE  u.Id = @UserId
       AND p.Id IS NOT NULL 
于 2014-02-26T19:13:32.417 回答