Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Why does this work...

DECLARE @MyInt int = 12345;
SELECT * FROM MyTable WHERE MyId = @MyInt; --Returns 1 row
SELECT * FROM MyTable WHERE MyId = 12345;  --Returns 1 row

but this doesn't?

DECLARE @MyVarchar varchar = 'ABCDEF';
SELECT * FROM MyTable WHERE MyId = @MyVarchar; --Returns 0 rows
SELECT * FROM MyTable WHERE MyId = 'ABCDEF';   --Returns 1 row

SQL Server version is 10.50.1746

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
200 views
Welcome To Ask or Share your Answers For Others

1 Answer

Because when you declare, default varchar length is 1. So @MyVarchar ends up being 'A'.

This is different to cast(something as varchar), where default length is 30.

The right thing is

DECLARE @MyVarchar varchar(10) = 'ABCDEF';

where 10 is the length of the column in the table.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...