如何从存储过程输入和临时表中将值插入表中

时间:2015-09-03 00:30:57

标签: sql sql-server sql-server-2008 stored-procedures

我有一个这样的存储过程:

create procedure spname
    @ID varchar,
    @name varchar,
    @R xml
AS
BEGIN
    -- Getting values XML
    create table #Table
    (
       country varchar,
       status varchar
    )

我必须根据以下条件将值插入表中:如果ID,Name来自存储过程输入和country(来自临时表)不存在,则插入。我不知道如何加入所有这些的确切语法。不过我试过下面,但我觉得它错了,我想我必须有一些像游标一样的循环技术?

DECLARE @Country VARCHAR;

SELECT @Country = C.Country 
FROM #Table C

INSERT INTO MyTable(Id, Name, Country)
VALUES (@Id, @Name, @Country)
FROM 
    WHERE NOT EXISTS (SELECT 1 FROM MyTable mT
                      WHERE ID = @Id
                        AND Name = @Name
                        AND mt.country = C.country)

我认为值中存在错误的语法,因为临时表包含很多值,所以它不能满足我的目的

我用这种方式想出了一个解决方案:

  DECLARE @country VARCHAR

    DECLARE CountryCur CURSOR FOR 
        SELECT Country FROM #Temp

    OPEN CountryCur 

    FETCH NEXT FROM CountryCur INTO @Country

    WHILE @@FETCH_STATUS = 0 
    BEGIN
        INSERT INTO MyTable(Id, Name, Country)
        VALUES (@id, @name, @Country)
        WHERE NOT IN (SELECT 1 FROM MyTable mT
                      WHERE mT.Id = @Id
                        AND mT.name = @name
                        AND mT.country = @Country)

        FETCH NEXT FROM CountryCur INTO @Country
        CLOSE CountryCur 
        DEALLOCATE CountryCur 

但是,它在哪里显示语法错误。不知道什么是错的。

2 个答案:

答案 0 :(得分:3)

正如你所提到的,#temp表中的数据来自xml,那么它应该像

一样简单
INSERT INTO MyTable(Id,Name,Country)
SELECT @Id, @Name, t.Country
FROM #Table t
WHERE NOT EXISTS (SELECT 1 
                  FROM MyTable mT
                  WHERE mt.ID = @Id
                    AND mt.Name = @Name
                    AND mt.country= t.country)

无需光标

答案 1 :(得分:-2)

您需要使用SELECT ... INTO而不是VALUES(),如下所示:

INSERT INTO MyTable(
            Id,
            Name,
            Country
        )
            select @ID, @Name, @Country
            WHERE not exists(select 1 from MyTable
                WHERE ID = @Id
                AND Name = @Name
                AND country in (Select country from #Temp))