patternsqlMinor
Is it better to populate variables using SET or SELECT?
Viewed 0 times
betterpopulateusingvariablesselectset
Problem
What is the better way (with regards to performance) to set a value to variable?
-
By
-
By
-
By
SET command:DECLARE @VarString nvarchar(max);
SET @VarString = 'john doe';
SELECT @VarString;-
By
SELECT command:DECLARE @VarString nvarchar(max);
SELECT @VarString = 'john doe';
SELECT @VarString;Solution
Don't pick one or the other strictly for performance.
Pick based on what fits your style and development needs, as is advised in the conclusion to this excellent comparison between
Best practice suggests not to stick to one method. Depending on the
scenario you may want to use both
Following are few scenarios for using
Using
Pick based on what fits your style and development needs, as is advised in the conclusion to this excellent comparison between
SELECT and SET (emphasis and minor formatting added):Best practice suggests not to stick to one method. Depending on the
scenario you may want to use both
SET or SELECT.Following are few scenarios for using
SET:- If you are required to assign a single value directly to variable and no query is involved to fetch value
- NULL assignments are expected (
NULLreturned in result set)
- Standards are meant to be follow for any planned migration
- Non scalar results are expected and are required to be handled
Using
SELECT is efficient and flexible in the following few cases:- Multiple variables are being populated by assigning values directly
- Multiple variables are being populated by single source (table , view)
- Less coding for assigning multiple variables
- Use this if you need to get
@@ROWCOUNTand@ERRORfor last statement executed
Context
StackExchange Database Administrators Q#17751, answer score: 8
Revisions (0)
No revisions yet.