Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this UN mean?

I wanted to do an insert into with a union, and someone suggested this:

SELECT x INTO ##temp
FROM (SELECT x FROM y UNION ALL SELECT x FROM z) UN

It works, but what is the UN? Unfortunately, Googling for "t-sql un" isn't very helpful :p

Note: I found out that you can just do SELECT x INTO ##temp FROM y UNION ALL SELECT x FROM b but I'm still curious about UN.

EDIT: Ok, so it's an alias, but why is it required to make this work? If I remove it, it won't execute.

like image 756
Brendan Long Avatar asked Nov 27 '25 16:11

Brendan Long


1 Answers

It's not a keyword. It's an alias. Any string could have been used there instead of "UN".

In more complete form, it is:

SELECT x INTO ##temp
FROM (SELECT x FROM y UNION ALL SELECT x FROM z) AS UN

@Tomalak is correct. In this case, the alias is required. Without the alias, the error is:

Msg 102, Level 15, State 1, Line 2 Incorrect syntax near ')'.

I simplified the query a bit and used the AdventureWorks database:

SELECT * INTO ##temp
FROM (SELECT * FROM Person.Address) 

this receives the error above. In contrast:

SELECT * INTO ##temp
FROM Person.Address

works just fine. An alternative is

;WITH UN AS
(
    SELECT * FROM Person.Address
)
SELECT * INTO ##temp
FROM UN
like image 182
John Saunders Avatar answered Nov 29 '25 04:11

John Saunders



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!