如何避免在表类型sql server中插入重复记录

时间:2014-08-05 08:27:47

标签: sql sql-server

我有这个查询表中的数据插入列表 现在我想避免插入重复记录 我怎么能在我的代码中做到这一点?

请帮帮我

-- Create a table type to match your input parameters
CREATE TYPE IdNameTable AS TABLE 
( ID INT, Name NVARCHAR(50) );
GO

-- change your stored procedure to accept such a table type parameter
ALTER PROCEDURE [dbo].[Register]
    @Values IdNameTable READONLY
AS
BEGIN
    BEGIN TRY
        INSERT INTO dbo.Group (Id, Name) 
          -- get the values from the table type parameter
          SELECT 
             Id, Name
          FROM
             @Values

        SELECT 0
    END TRY
    BEGIN CATCH
        SELECT -1
    END CATCH
END
GO

4 个答案:

答案 0 :(得分:5)

尝试这种方式:

INSERT INTO dbo.Group (Id, Name) 
SELECT 
  Id, Name
FROM
  @Values
WHERE 
  ID NOT IN (select ID from Group)

完整代码:

-- Create a table type to match your input parameters
CREATE TYPE IdNameTable AS TABLE 
( ID INT, Name NVARCHAR(50) );
GO

-- change your stored procedure to accept such a table type parameter
ALTER PROCEDURE [dbo].[Register]
    @Values IdNameTable READONLY
AS
BEGIN
    BEGIN TRY

        INSERT INTO dbo.Group (Id, Name) 
        SELECT 
           Id, Name
        FROM
           @Values
        WHERE 
           ID NOT IN (select ID from Group)

        SELECT 0
    END TRY
    BEGIN CATCH
        SELECT -1
    END CATCH
END
GO

答案 1 :(得分:1)

我使用NOT EXISTS来检查dbo.Group表中是否有ID,并且只有在找不到匹配项时才插入。假设ID是唯一的。请根据需要将Not EXISTS内的过滤器修改为tiler。希望它有所帮助

CREATE TYPE IdNameTable AS TABLE 
(ID INT, NAME NVARCHAR(50));
GO

-- change your stored procedure to accept such a table type parameter
ALTER PROCEDURE [dbo].[Register]
    @Values IdNameTable READONLY
AS
BEGIN
    BEGIN TRY
        INSERT INTO dbo.Group (Id,NAME)
        -- get the values from the table type parameter
        SELECT   v.Id,
                 v.NAME
        FROM     @Values v
        WHERE NOT EXISTS (SELECT 1 FROM dbo.Group gp WHERE gp.id=v.id)

        SELECT   0
    END TRY
    BEGIN CATCH
        SELECT   -1
    END CATCH
END
GO

答案 2 :(得分:1)

最简单的方法是在创建表格时向字段添加唯一约束 创建表tble_Name ( ID int identity(1,1), 名称nvarchar(50)唯一 Null ) 当您输入记录时,查询应防止重复记录

答案 3 :(得分:-1)

CREATE TYPE IdNameTable AS TABLE 
(ID INT, NAME NVARCHAR(50));
GO

-- change your stored procedure to accept such a table type parameter
ALTER PROCEDURE [dbo].[Register]
    @Values IdNameTable READONLY
AS
BEGIN
    BEGIN TRY
        INSERT INTO dbo.Group (Id,NAME)
        -- get the values from the table type parameter
        SELECT   v.Id,
                 v.NAME
        FROM     @Values v
        WHERE NOT EXISTS (SELECT 1 FROM dbo.Group gp WHERE gp.id=v.id)

        SELECT   0
    END TRY
    BEGIN CATCH
        SELECT   -1
    END CATCH
END
GO