简体   繁体   中英

Select a column by condition in Insert query

I want to insert data into one column based on condition.

DECLARE @section NVARCHAR(40)
SET @section ='section1'

INSERT [table]
   (
       Class_Of_Business,
       Financial_Status,
       Source_Of_Funds,
       Source_Of_Wealth,
           SELECT CASE 
               WHEN @Section = 'section1' THEN  'Section_1_Operator_Comments' 
               WHEN @Section = 'section2' THEN  'Section_2_Operator_Comments' 
               ELSE 'Section_3_Operator_Comments' END
   )
VALUES ('Private','Good','bank','Business','section comments')

based on the user input

comments(section1, section2 or section3)

need to insert in respective column.

Try this:

DECLARE @section NVARCHAR(40)
SET @section ='section1'

INSERT [table]
(
   Class_Of_Business,
   Financial_Status,
   Source_Of_Funds,
   Source_Of_Wealth,
   Section_1_Operator_Comments,
   Section_2_Operator_Comments,
   Section_3_Operator_Comments
)
VALUES ('Private','Good','bank','Business',
       CASE WHEN @Section = 'section1' THEN 'section comments' else NULL END,
       CASE WHEN @Section = 'section2' THEN 'section comments' else NULL END,
       CASE WHEN @Section = 'section3' THEN 'section comments' else NULL END 
)

You can't do it like this. You can either use dynamic SQL to create your insert statement or use a insert...select (which I think is a better approach):

INSERT INTO [table] 
(
    Class_Of_Business, 
    Financial_Status, 
    Source_Of_Funds, 
    Source_Of_Wealth,
    Section_1_Operator_Comments, 
    Section_2_Operator_Comments, 
    Section_3_Operator_Comments 
)
SELECT  'Private',
        'Good',
        'bank',
        'Business',
        CASE WHEN @Section = 'section1' THEN 'section comments' END, -- else will return NULL by default
        CASE WHEN @Section = 'section2' THEN 'section comments' END, 
        CASE WHEN @Section NOT IN('section1', 'section2') THEN 'section comments' END 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM