SQL Server - 来自简单愚蠢查询的差异结果?

时间:2015-12-17 15:29:35

标签: sql sql-server

为什么这些简单的查询会返回不同的结果?只有差异为@val

查询#1:

DECLARE @val NVARCHAR
BEGIN
    SET @val = '0320'

    SELECT 1
    WHERE CAST(SUBSTRING(@val, 3, 2) AS INT) + 2000 < YEAR(GETDATE())
END

查询#2:

SELECT 1
WHERE CAST(SUBSTRING('0320', 3, 2) AS INT) + 2000 < YEAR(GETDATE())

1 个答案:

答案 0 :(得分:8)

由于您尚未声明NVARCHAR变量的大小,因此在第一个示例中,@val的内容为&#39; 0&#39;而不是&#39 ; 0320&#39 ;.

要解决此问题,请使用DECLARE @val NVARCHAR(10)

DECLARE @val NVARCHAR(10)
BEGIN
  SET @val = '0320'
  SELECT 1
  WHERE CAST(SUBSTRING(@val, 3, 2) AS INT) + 2000 < YEAR(GETDATE())
END