Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server Management Studio declaring variable [duplicate]

I was doing the following in SQL Server Management Studio

declare @datestring varchar;

BEGIN
   set @datestring ='18/04/2015'
   select @datestring
END

Enough surprisingly for me, the result is 1.

Can someone please explain this?

like image 793
yi.han Avatar asked Jul 08 '26 08:07

yi.han


2 Answers

Try to declare by giving the length to varchar

declare @datestring varchar(10);

If you will not provide any length to varchar then it would default to 1.

From the MSDN:

When n is not specified in a data definition or variable declaration statement, the default length is 1. When n is not specified when using the CAST and CONVERT functions, the default length is 30.

like image 82
Rahul Tripathi Avatar answered Jul 10 '26 22:07

Rahul Tripathi


When using the text type variables you should explicitly set the length of the variable:

declare @datestring varchar(10);
BEGIN
    set @datestring ='18/04/2015'
    select @datestring
END

If you do not specify the length it is identical to varchar(1) as described in Remarks section of this MSDN article:

When n is not specified in a data definition or variable declaration statement, the default length is 1. When n is not specified when using the CAST and CONVERT functions, the default length is 30.

like image 44
dotnetom Avatar answered Jul 10 '26 21:07

dotnetom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!