SQL删除不在的地方

Mar*_*nHN 6 sql sql-server

我有一个像这样的关系映射表:

属性bigint
productid bigint

要清除不再使用的关系,我想删除其中productid = x和attributeid不在(@includedIds)的所有recors,如下例所示:

@attributetypeid bigint, 
@productid bigint,
@includedids varchar(MAX)  


DELETE FROM reltable 
WHERE productid = @productid AND 
attributetypeid = @attributetypeid AND 
attributeid NOT IN (@includedids);
Run Code Online (Sandbox Code Playgroud)

当使用包含多于1个id的includedids param运行SQL时 - 像这样:25,26 - 我得到一个SqlException说:

将数据类型varchar转换为bigint时出错.

这当然是由于varchar(max)参数...

我应该如何构建我的删除语句以使其工作?

kar*_*grz 2

  SET QUOTED_IDENTIFIER ON
  GO
  CREATE FUNCTION [dbo].[ListToTable] (
  /*
  FUNCTION ListToTable
  Usage: select entry from listtotable('abc,def,ghi') order by entry desc
  PURPOSE: Takes a comma-delimited list as a parameter and returns the values of that list into a table variable.
  */
  @mylist varchar(8000)
  )
  RETURNS @ListTable TABLE (
  seqid int not null,
  entry varchar(255) not null)

  AS

  BEGIN
      DECLARE 
          @this varchar(255), 
          @rest varchar(8000),
          @pos int,
          @seqid int

      SET @this = ' '
      SET @seqid = 1
      SET @rest = @mylist
      SET @pos = PATINDEX('%,%', @rest)
      WHILE (@pos > 0)
      BEGIN
          set @this=substring(@rest,1,@pos-1)
          set @rest=substring(@rest,@pos+1,len(@rest)-@pos)
          INSERT INTO @ListTable (seqid,entry)  VALUES (@seqid,@this)
          SET @pos= PATINDEX('%,%', @rest)
          SET @seqid=@seqid+1
      END
      set @this=@rest
      INSERT INTO @ListTable (seqid,entry) VALUES (@seqid,@this)
      RETURN 
  END
Run Code Online (Sandbox Code Playgroud)

在 SQL Server 数据库中运行该脚本以创建函数 ListToTable。现在,您可以像这样重写查询:

@attributetypeid bigint, 
@productid bigint,
@includedids varchar(MAX)  


DELETE FROM reltable 
WHERE productid = @productid AND 
attributetypeid = @attributetypeid AND 
attributeid NOT IN (SELECT entry FROM ListToTable(@includedids));
Run Code Online (Sandbox Code Playgroud)

其中 @includedids 是您提供的逗号分隔列表。我在处理列表时一直使用这个函数。请记住,此函数不一定会清理您的输入,它只是在逗号分隔列表中查找字符数据并将每个元素放入记录中。希望这可以帮助。