创建表并使用合并填充

时间:2012-03-08 19:52:36

标签: sql sql-server-2008

我有一个SQL 2008 R2表,包含(col1(char),col2(int,prim key),col3(char))。

我用...填充表格。

MERGE [dbo].[Data] as target
USING 
(
SELECT 01, 1, 'Data1'
UNION ALL 
SELECT 03, 2, 'Data2'
UNION ALL 
SELECT D2, 3, 'Data3'
)AS source ([Col1], [Col2], [Col3])
ON (target.[Col2] = source.[Col2])
WHEN MATCHED THEN 
    UPDATE SET [Col1] = source.[Col1],
               [col3] = source.[col3]
WHEN NOT MATCHED THEN   
    INSERT ([col1], [col2], [col3])
    VALUES (source.[col1],source.[col2], source.[col3]);

除了“SELECT D2,3,'Data3'”语句之外,它填充正常,并抛出无效的列名。任何想法为什么或如何解决它?

由于

2 个答案:

答案 0 :(得分:2)

您需要将此小字符添加到col1:'

MERGE [dbo].[Data] as target
USING 
(
SELECT '01' Col1, 1 Col2, 'Data1' Col3
UNION ALL 
SELECT '03', 2, 'Data2'
UNION ALL 
SELECT 'D2', 3, 'Data3'
)AS source ([Col1], [Col2], [Col3])
ON (target.[Col2] = source.[Col2])
WHEN MATCHED THEN 
    UPDATE SET [Col1] = source.[Col1],
               [col3] = source.[col3]
WHEN NOT MATCHED THEN   
    INSERT ([col1], [col2], [col3])
    VALUES (source.[col1],source.[col2], source.[col3]);

答案 1 :(得分:1)

引号中需要D2,如下所示:'D2',如果是字符串。如果它是表格中的列,则需要执行SELECT D2, 3, 'Data3' FROM <table>