CELKO (10/2/2012)
...
Why would anyone create a local variable (like we did in 1950's assembly languages) to hold the results of an expression. We just use the expression itself in declarative languages.
...
YOU, may be do, but WE don't! Most of modern languages do have concept of "variable" and T-SQL is one of them.
Many T-SQL experts don't ALWAYS use expression itself in a declarative languages such as T-SQL which allows to hold intermediate result in a variable. For example (as per given OP post) if you want to get one single record ID and then reuse it multiple times within process, the use of variable is more than reasonable!
CELKO (10/2/2012)
...
Actually, we use the ANSI/ISO Standard SET for assignment and not the old 1970's Sybase SELECT. The SELECT assignment has cardinality problems. Now look at where you did the assignment to the fake assembly language register you did with a local variable.
YOU, may be ALWAYS do, but WE don't! Before SQL2008 allowed to initialise variables in time of declaration, many T-SQL experts very often used single SELECT statements to initialise multiple variables at once. Even now, it is used widely for initialising variables from relevant table/query.
Actually, you kind of contradict yourself: if you would never create a local variable (like you did in 1950's assembly languages) to hold the results of an expression why ANSI have a SET?
But what is important to understand is how SELECT behaves when it's used for setting variables.
Let see this:
DECLARE @name VARCHAR(255) = 'xxxx'
SELECT @name = (SELECT name FROM sys.columns WHERE name like 'a%')
SELECT @name
What would be possible results of this query? It depends!
1. If no records found in sys.columns the value of @name will be reset to NULL
2. If single record found in sys.columns the value of @name will set the [name] returned by select
3. If multiple records found in sys.columns you will get run-time error "Subquery returned more than 1 value..."
I'do, personally, really hate this behaviour, so I never using this sort of logic. Instead I am using SELECT per following:
DECLARE @name VARCHAR(255) = 'xxxx'
SELECT @name = name FROM sys.columns WHERE name like 'a%'
SELECT @name
In this case:
1. If no records found in sys.columns the value of @name is not reset to NULL, so initialise value stays
2. If single record found in sys.columns the value of @name will set the [name] returned by select
3. If multiple records found in sys.columns you will NOT cause get run-time error and will be set to one of values returned by SELECT (you cannot guarantee which one)
Here is #3 requires a special attention.
if your SELECT may potentially return multiple record (as per given example), then such initialising query is most likely is not appropriate at all! However, there are some cases where it's really doesn't meter, so it can be used safely without causing run-time errors.