Adding INSERT statement inside the CASE WHEN condi

2019-08-07 08:52发布

问题:

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.

回答1:

INSERT INTO [DestinationTable]
SELECT
    [MyColumn1]
FROM
    [SourceTable]
WHERE
    @ID = 2 AND
    Stud.Status = 'N'


回答2:

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