Manioth Shijith Manioth Shijith - 1 year ago 57
SQL Question

Conditionally assign value to sql variable

Is there any way to conditionally assign value to a variable in sql server, Like

SET SDate = Isnull((Select StartDate from SData), Select EDate from Table2)

If the first query return null or no record exist it should pick up value from tabl2.

Answer Source

Your version is pretty close. You can write this as:

SET SDate = Isnull((Select StartDate from SData),
                   (Select EDate from Table2)

A subquery always needs to be surrounded by its own parentheses.

That said, your query presupposes that both tables have at most one row. This does not seem like a good assumption. If either has more than one row, you'll get a "subquery returns more than one row" error.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download