HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Using X at the end of a SELECT in SQL Server Script?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
scriptthesqlusingendserverselect

Problem

I'm relatively new to T-SQL and looking through my predecessors scripts, I found a line I can't quite parse. It's a hard thing to look up on my own. Hoping for advice.

This line occurs inside a WHILE loop, but I don't think that matters. I believe functionally, that this is gathering the values from a column across a few rows that share an ID and concatenating them with commas into 1 field. But I don't know what this is called or how to look it up to use it myself.

What is this 'x' doing at the end? Can anyone point me to information on this?

(select @invtid = coalesce(@invtid + ',',' ')+rtrim(RoleID) 
FROM (
    Select distinct roleid 
    from UserAccounts 
    WHERE CustID = @custID
     )
 x)


Thanks.

Solution

The "X" is an alias for the following portion:

Select distinct roleid 
from UserAccounts 
WHERE CustID = @custID


So you'd be able to use it as:

SELECT x.roleid
FROM  
(    Select distinct roleid 
from UserAccounts 
WHERE CustID = @custID) x
where x.roleid >100


In the grand scheme of things, your query would look like:

(select @invtid = coalesce(@invtid + ',',' ')+rtrim(x.RoleID) 
 FROM (
    Select distinct roleid 
    from UserAccounts 
    WHERE CustID = @custID
     )x
 )


technically you can use anything as your Alias. "X", usually a more descriptive alias works. Something like "roles"

Code Snippets

Select distinct roleid 
from UserAccounts 
WHERE CustID = @custID
SELECT x.roleid
FROM  
(    Select distinct roleid 
from UserAccounts 
WHERE CustID = @custID) x
where x.roleid >100
(select @invtid = coalesce(@invtid + ',',' ')+rtrim(x.RoleID) 
 FROM (
    Select distinct roleid 
    from UserAccounts 
    WHERE CustID = @custID
     )x
 )

Context

StackExchange Database Administrators Q#182889, answer score: 8

Revisions (0)

No revisions yet.