I want to union 3 different statements, the problem is that I am using a loop and if in my query:
WHILE some condition
BEGIN
if(condition 1)
begin
select something
end
else if(condition 2)
begin
select something
end
else if(condition 3)
begin
select something
end
END
The query is working fine but it returns more than 100 different select results (distin开发者_如何学JAVAct tables). How can I union these select results into one table?
If you mean in TSQL, then you need a temporary table (#foo
) or table variable (@bar
). Then at each step:
INSERT {name} ({cols})
SELECT {cols}
{etc}
Then do a final
SELECT {cols}
FROM {name}
The choice between table-variable and temporary-table is subtle. I prefer table-variables; but for large data, or if you need an identity/index, a temporary-table may be more versatile. But if you aren't inside a SPROC you must ensure you clean up your temp table.
精彩评论