如何根据参数运行两个不同的SELECT查询之一。
if (x=1)
then
SELECT Product_Name, Pro_ID FROM Store
else
SELECT [Product_Name] FROM [Store] WHERE (Supplier_ID = 3)
答案 0 :(得分:1)
您可以在以下网址中使用 IF :
IF (@x = 1)
BEGIN
SELECT Product_Name, Pro_ID FROM Store
END
ELSE
BEGIN
SELECT [Product_Name] FROM [Store] WHERE (Supplier_ID = 3)
END
或更短的方式:
IF (@x = 1)
SELECT Product_Name, Pro_ID FROM Store
ELSE
SELECT [Product_Name] FROM [Store] WHERE (Supplier_ID = 3)
答案 1 :(得分:1)
可能是下面的代码会有用。如果我理解正确。这个代码在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
)