在SQL Server中将数据类型nvarchar转换为bigint时出错

时间:2015-08-18 19:15:38

标签: sql sql-server-2008

为什么查询#2给我一个错误,将数据类型nvarchar转换为bigint?

查询#1:

SELECT CAST(CAST(AsnNumber AS bigint) AS nvarchar(33)) AS AsnNumber 
FROM [DB1].Schema1.Table1 (nolock)

尝试使用转换,但得到相同的错误:

SELECT Convert(nvarchar(33), Convert(bigint, AsnNumber)) AS AsnNumber 
FROM [DB1].Schema1.Table1 (nolock)

查询#2:

SELECT AsnNumber
FROM Query1
WHERE AsnNumber = '1777188'

此处AsnNumber的类型为nvarchar(33)Table1

中为null

1 个答案:

答案 0 :(得分:1)

我把它作为一个答案,即使它没有真正回答这个问题,因为我无法在评论中恰当地适应这一点。

我针对SQL Server 2008运行此操作,我没有收到任何错误..

BEGIN
  DECLARE @t TABLE(AsnNumber NVARCHAR(33))

  INSERT INTO @t (AsnNumber) VALUES('1777188')
  INSERT INTO @t (AsnNumber) VALUES('1777189')

  SELECT AsnNumber FROM @t

  SELECT CAST(AsnNumber AS BIGINT) as AsnNumber 
  FROM @t
  WHERE AsnNumber = '1777188';

  SELECT CAST(CAST(AsnNumber AS BIGINT) AS NVARCHAR(33)) as AsnNumber 
  FROM @t
  WHERE AsnNumber = '1777188';

  SELECT query1.*
  FROM (SELECT CAST(CAST(AsnNumber AS BIGINT) AS NVARCHAR(33)) as AsnNumber FROM @t) as query1
  WHERE AsnNumber = '1777188';

  WITH query1 (AsnNumber) AS 
  (SELECT CAST(CAST(AsnNumber AS BIGINT) AS NVARCHAR(33)) as AsnNumber FROM @t)
  SELECT AsnNumber FROM query1
  WHERE AsnNumber = '1777188';

END

这表明您的查询#1工作正常,它还演示了我可以将它用作子查询,我可以在公用表表达式中使用它,但仍然没有错误。我不知道你为什么会收到错误。

也许您可以包含一整套语句来创建表,用数据填充它,然后运行产生错误的确切查询?如果你这样做,它将帮助我重现这个问题,然后我可以解释它为什么会发生。目前,我无法重现您的问题。