Reputation: 4966
Why is query #2 giving me an error converting data type nvarchar to bigint?
Query #1:
SELECT CAST(CAST(AsnNumber AS bigint) AS nvarchar(33)) AS AsnNumber
FROM [DB1].Schema1.Table1 (nolock)
Tried with Convert as well, but get the same error:
SELECT Convert(nvarchar(33), Convert(bigint, AsnNumber)) AS AsnNumber
FROM [DB1].Schema1.Table1 (nolock)
Query #2:
SELECT AsnNumber
FROM Query1
WHERE AsnNumber = '1777188'
Here AsnNumber
is of type nvarchar(33)
, null in Table1
Upvotes: 1
Views: 13881
Reputation: 6881
I'm putting this as an answer, even though it doesn't really answer the question, because I can't fit this properly in a comment.
I ran this against SQL Server 2008 and I don't get any errors..
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
This demonstrates that your query #1 works fine, and it also demonstrates that I can use it as a subquery and I can use it in a common table expression, and still no error. I have no idea why you're getting an error.
Perhaps you can include a full set of statements to create the table, populate it with data, and then the exact query you're running that produces the error? If you do that, it would help me to reproduce the issue, and then I could probably explain why it's occurring. For now, I can't reproduce your issue.
Upvotes: 1