Home

Size should be specified for varchar variables and parameters

Description

    The "Size should be specified for varchar variables and parameters" rule for SQL Server code states that when declaring variables and parameters of the varchar data type, the size of the variable or parameter should be specified. This helps ensure that the data stored in the variable or parameter is of the correct size and that it does not exceed the maximum size of the data type. Without specifying a size, the data stored in the variable or parameter could be truncated or cause an error when it exceeds the maximum size of the data type.

Key Benefits

  • Specify the size of data: By specifying the size of the data, it ensures that only the required amount of data is stored and processed, thus reducing the amount of memory and processing time needed.
  • Reduce Memory and Processing Time: By specifying the size of the data, it ensures that only the required amount of data is stored and processed, thus reducing the amount of memory and processing time needed.
  • Ensure Data Quality: Specifying the size of the data also ensures data quality, as it prevents data that is too large from being stored, which can lead to errors.
  • Prevent Security Issues: Specifying the size of the data can also help to prevent security issues, as it can prevent malicious data from being stored in the database.

 

Non-compliant Code Example

DECLARE @find varchar;   --Non compliant code (Variable declared as a varchar without size)
SET @find = 'Man%';   
SELECT p.LastName, p.FirstName, ph.PhoneNumber  
FROM Person.Person AS p   
JOIN Person.PersonPhone AS ph ON p.BusinessEntityID = ph.BusinessEntityID  
WHERE LastName LIKE @find;

Compliant Code Example

DECLARE @find varchar(30);   --Compliant code (Variable declared as a varchar with size)
SET @find = 'Man%';   
SELECT p.LastName, p.FirstName, ph.PhoneNumber  
FROM Person.Person AS p   
JOIN Person.PersonPhone AS ph ON p.BusinessEntityID = ph.BusinessEntityID  
WHERE LastName LIKE @find;  
Visual Expert 2024
 VETSQLRULE8