Ayman Ayman - 6 months ago 10
SQL Question

Run one of two different SELECT queries based on declared value

How can i run one of two different SELECT queries based on parameter for example.

if (x=1)
then
SELECT Product_Name, Pro_ID FROM Store
else
SELECT [Product_Name] FROM [Store] WHERE (Supplier_ID = 3)

Answer

May be the below code will be useful. If I understood you correctly.This code is working fine in SQL Server 2012

--Creating a Table.
CREATE TABLE #MyTable 
    (
    Column1 VARCHAR(10), 
    Column2 VARCHAR(10),
    OptionalColumn VARCHAR(10)
    )
--Inserting value to the Table.
INSERT INTO #MyTable
VALUES('Value 1', 'Value 1','Optional Value')

--IF ELSE Logic to desired output.
DECLARE @Check bit 
SET @Check = 0

IF @Check = 1 
    (
    SELECT 
        Column1, 
        Column2
    FROM 
        #MyTable
    )
ELSE
   (
    SELECT 
        Column1, 
        Column2,
        OptionalColumn
    FROM 
        #MyTable
    )