2017-07-25 73 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