Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UNION inside IF EXISTS statement not working

Tags:

sql

union

SELECT A, B, C FROM TUser

UNION

IF EXISTS(SELECT dataUserId FROM TUserData WHERE DataId = @dataId AND UserId = @userId)
  BEGIN
    SELECT @dataUserId  = dataUserId FROM TUserData WHERE DataId = @dataId AND UserId = @userId

    SELECT A, B, C FROM TUser WHERE UserId = dataUserId 
  END
like image 768
spj Avatar asked Mar 10 '10 07:03

spj


People also ask

How to check exist condition in SQL?

The result of EXISTS is a boolean value True or False. It can be used in a SELECT, UPDATE, INSERT or DELETE statement. Syntax: SELECT column_name(s) FROM table_name WHERE EXISTS (SELECT column_name(s) FROM table_name WHERE condition);

What does the UNION Operator do in SQL statement?

The SQL UNION Operator The UNION operator is used to combine the result-set of two or more SELECT statements.

WHERE EXISTS SELECT FROM subquery?

The subquery is a SELECT statement. If the subquery returns at least one record in its result set, the EXISTS clause will evaluate to true and the EXISTS condition will be met. If the subquery does not return any records, the EXISTS clause will evaluate to false and the EXISTS condition will not be met.


2 Answers

You can transform it like that:

SELECT @dataUserId  = dataUserId FROM TUserData
WHERE DataId = @dataId AND UserId = @userId

IF (@dataUserId IS NOT NULL)
  BEGIN
    SELECT A, B, C FROM TUser
    UNION
    SELECT A, B, C FROM TUser WHERE UserId = @dataUserId 
  END
ELSE
  SELECT A, B, C FROM TUser
like image 159
Kerido Avatar answered Sep 19 '22 18:09

Kerido


That is invalid SQL. It appears that you are trying to write something like a function/stored-procedure.

This is how UNION works (http://www.w3schools.com/SQL/sql_union.asp):

SELECT column_name(s) FROM table_name1
UNION
SELECT column_name(s) FROM table_name2

Both SELECT statements must have the same number of columns. The columns must also have similar data types. Also, the columns in each SELECT statement must be in the same order.

like image 28
Timothy Avatar answered Sep 19 '22 18:09

Timothy