2017-07-25 75 views
1

我想根据条件将数据插入到一列中。在插入查询条件中选择一列

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') 

基于用户输入

注释(SECTION1,第2节或SECTION3)

需要在各列中插入。

+2

为您的DBMS添加标记。也许Sql Server? –

回答

0

试试这个:

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 
) 
+0

美丽的回答:-) –

+0

@ZoharPeled:谢谢亲爱的,因为你的! –

0

你不能像这样做。您可以使用动态SQL创建插入语句或使用插入... select(我认为这是更好的方法):

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