2014-03-27 112 views
0

僅供參考,如果您想閱讀: (我正在研究SQL數據庫更新程序,我有一個(舊)ICD代碼表,並且我想插入新記錄(約90k記錄),如果沒有已存在的ICD代碼,則插入,如果是,則更新。問題是要插入的數據來自表格調用IcdImportData(從.csv文件導入),我需要創建變量表包含舊錶和新IMPORTDATA表的比較值)SQL從SELECT結果插入表變量

我想諮詢一下: 我想插入值變量表,SELECT語句日在返回許多記錄。我怎樣才能做到這一點?

這是代碼:

SELECT IcdCodeID FROM 
(
    SELECT IcdCodeID FROM IcdImportData 
    UNION ALL 
    SELECT IcdCodeValue FROM IcdCode 
) tmp 
GROUP BY IcdCodeID 
HAVING COUNT(*)>=2 

,我想結果插入到這個變量表:

DECLARE @temp table (IcdCodeValue NCHAR(10)) 
INSERT INTO @temp 
SELECT 
(
*The code above* 
) 

的錯誤:

Msg 512, Level 16, State 1, Line 2 Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression. The statement has been terminated.

+1

見'INSERT'語法爲您的RDBMS – Alexander

+1

請表明發生故障的實際INSERT語句。另外,這是什麼數據庫? – 2014-03-27 07:31:38

回答

0

這個工作,你有刪除一個額外的select

DECLARE @temp table (IcdCodeValue NCHAR(10)) 

INSERT INTO @temp 
SELECT IcdCodeID FROM 
(
     SELECT IcdCodeID FROM IcdImportData 
     UNION ALL 
     SELECT IcdCodeValue FROM IcdCode 
) tmp 
GROUP BY IcdCodeID 
HAVING COUNT(*)>=2 

或做這種方式

DECLARE @temp table (IcdCodeValue NCHAR(10)) 
INSERT INTO @temp 
SELECT * FROM 
(
SELECT IcdCodeID FROM 
(
     SELECT IcdCodeID FROM IcdImportData 
     UNION ALL 
     SELECT IcdCodeValue FROM IcdCode 
) tmp 
GROUP BY IcdCodeID 
HAVING COUNT(*)>=2) t 
+0

謝謝,這個作品! –