Insert into a temporary table using a CASE statement
I need to create and populate a temporary table at the start of a stored procedure. I need to populate the table in one of two ways depending on whether a parameter passed to the stored procedure is NULL or not.
The below pseudo-SQL is what I want to do. The fnSplit is a custom function that splits the string on the ',' character and returns table ([Value] nvarchar(4000)).
DECLARE @ids varchar(max)
DECLARE @orders TABLE
(
ProductID int,
BrandID int
)
IF ISNULL(@ids)
INSERT INTO @orders
SELECT
PO.ProductID,
PO.BrandID
FROM dbo.ProductOrders PO
ELSE
INSERT INTO @orders
SELECT
PO.ProductID,
PO.BrandID
FROM fnSplit( @ids, ',')
JOIN dbo.ProductOrders PO on Value = PO.ID
END
How can I acheive the above with vaid SQL? Perhaps using a CASE statement? Note the main logic i开发者_开发问答n the stored procedure follows after this block and makes use of the @orders table.
You got pretty close
IF @ids IS NULL
BEGIN
INSERT INTO @orders
SELECT
PO.ProductID,
PO.BrandID
FROM dbo.ProductOrders PO
END ELSE BEGIN
INSERT INTO @orders
SELECT
PO.ProductID,
PO.BrandID
FROM fnSplit( @ids, ',')
JOIN dbo.ProductOrders PO on Value = PO.ID
END
精彩评论