Adding INSERT statement inside the CASE WHEN condi

2019-08-07 09:13发布

My Code:

   'Status' = 
       CASE  
           WHEN @ID = 2 AND Stud.Status = 'N' THEN 'To Be Submitted'
           WHEN Stud.Status = 'N' THEN 'N/A' 
           ELSE ISNULL(Stud.Status, '') 
        END

I want to add an Insert statement if the first condition is satisfied, That is, after the following code. How to add an Insert statement here.

WHEN @ID = 2 AND Stud.Status = 'N' THEN 'To Be Submitted'

Thanks.

2条回答
Anthone
2楼-- · 2019-08-07 09:29

I would make your query into a Store Procedure, add your first query to a temp table and then split it into what you need... for example:

DECLARE @TempTable TABLE (Name NVARCHAR(50), Status NVARCHAR(50))

INSERT INTO @TempTable
SELECT Name, 
   CASE  
       WHEN @ID = 2 AND Stud.Status = 'N' THEN 'To Be Submitted'
       WHEN Stud.Status = 'N' THEN 'N/A' 
       ELSE ISNULL(Stud.Status, '') 
    END as Status
FROM [Table]
WHERE [column] = 'value';

and then use that temp table to perform your insert

INSERT INTO [MyTable]
SELECT TOP 1 Name, Status 
FROM @TempTable
WHERE Status = 'To Be Submitted';

This way you are only inserting what you need as

I want to add an Insert statement if the first condition is satisfied

TOP 1 will make sure of that

查看更多
女痞
3楼-- · 2019-08-07 09:32
INSERT INTO [DestinationTable]
SELECT
    [MyColumn1]
FROM
    [SourceTable]
WHERE
    @ID = 2 AND
    Stud.Status = 'N'
查看更多
登录 后发表回答