Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL conditional union

Tags:

sql

sql-server

Question: I have an SQL function which returns a list of files

now I should join an additional list to that list with an union, but only if the user is admin.

Is that possible? Something like:

CREATE FUNCTION tfu_CMS_Process(@bIsAdmin bit  )
-- Add the parameters for the function here
RETURNS TABLE
AS
RETURN
 (
 SELECT * FROM TABLE1

 if bIsAdmin

 UNION ALL 

 SELECT * FROM TABLE2

 end if
 )
like image 615
Stefan Steiger Avatar asked Dec 11 '09 16:12

Stefan Steiger


People also ask

What is the condition for union in SQL?

Every SELECT statement within UNION must have the same number of columns. The columns must also have similar data types. The columns in every SELECT statement must also be in the same order.

Can we use 3 Union in SQL?

Combining several tables to one large table is possible in all 3 ways. As we have seen, the behavior of UNION in SQL Server and UNION in DAX within Power BI is very similar. Here tables with the same number of columns are placed directly under each other.

Do UNION SQL clause can be used with?

The SQL UNION clause/operator is used to combine the results of two or more SELECT statements without returning any duplicate rows. But they need not have to be in the same length.

How do you join a union in SQL?

JOIN. The join such as INNER JOIN or LEFT JOIN combines columns from two tables while the UNION combines rows from two queries. In other words, join appends the result sets horizontally while union appends the result set vertically.


1 Answers

SELECT  *
FROM    table1
UNION ALL
SELECT  *
FROM    table2
WHERE   @isAdmin = 1
like image 144
Quassnoi Avatar answered Oct 10 '22 23:10

Quassnoi