Tuesday, January 17, 2012

SQL Data type, Varchar without N

When we declare variable as varchar, we will :
Declare part as varhcar(20)

What if we declare varchar without indicate the length?
Declare part as varchar


See the below example :

DECLARE @myVariable AS varchar
DECLARE @myNextVariable AS varchar(10)
SET @myVariable = 'abc'
SET @myNextVariable = 'abc'
SELECT DATALENGTH(@myVariable), DATALENGTH(@myNextVariable);
--result    1           3
SELECT @myVariable, @myNextVariable;
--result a    abc
GO


Remarks
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.


Examples:
SPROC_TEST 'FINAL'

Create  PROCEDURE [dbo].[SPROC_TEST]
@submission_type VARCHAR -- START, FINAL
AS
print @submission_type
BEGIN
     IF  @submission_type='FINAL'
        PRINT 'A'
      ELSE
        PRINT 'B'
END


We pass parameter as ‘FINAL’ and expected “A’ will be printed,
We will get result result ‘B’ (not as expected), because value in @submission_type been truncate to “F”

Reference
http://msdn.microsoft.com/en-us/library/ms176089.aspx