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
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);
The SQL UNION Operator The UNION operator is used to combine the result-set of two or more SELECT statements.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With