开发者

Insert into a temporary table using a CASE statement

开发者 https://www.devze.com 2023-02-10 22:58 出处:网络
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 N

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
0

精彩评论

暂无评论...
验证码 换一张
取 消