如何在SQL中获取可选的参数

时间:2018-11-18 12:12:07

标签: sql sql-server

我需要等待获取表名和fildes名称列表的过程,以比较和传递比较该fildes的所有重复行

如何获取参数列表-可选?

CREATE PROCEDURE DeleteDuplicateRows 
      @tableName NVARCHAR(MAX) not null,
      @nameFildes ???, 
AS
BEGIN

     DECLARE @sql NVARCHAR(MAX)

     set @sql = 'delete from '+@tableName+
            'where '+ ????
     EXEC sp_executesql @Sql


END

2 个答案:

答案 0 :(得分:0)

我认为您正在寻找一种传递多个值的方法;即您可以将多个字段名称设为零。为此,与其查看选项参数,不如传递一个长度为零或更大的“数组”。为此,您可以声明自己的类型,该类型表示一个表,该表包含一列nvarchar字符,例如:

create type StringArrayType as table   
(
    value nvarchar(max) not null
)  
go
create procedure DeleteDuplicateRows 
      @tableName NVARCHAR(MAX),
      @fieldNames StringArrayType readonly
AS
begin

     DECLARE @sql NVARCHAR(MAX)

     select @sql = coalesce(@sql + ', ', '') + quotename(value)
     from @fieldNames

     --this deletes all values of any row with duplicates (i.e. including the original)
     --To only delete the duplicates and not the original, look at using row_number() or similar 
     --(many examples exist on SO already, and that's not what you've asked about, so I'll only provide this version for this example)
     set @sql = 'delete from ' + quotename(@tableName) + coalesce(' group by ' + @sql + ' having count(1) > 1','')

     select @sql SqlStatement --for now just return the SQL
     --EXEC sp_executesql @Sql

end
go
declare @fields StringArrayType;

insert @fields (value) values ('One'),('Two');

exec DeleteDuplicateRows 'myTable', @fields;

此代码的小提琴可以在这里找到:https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=477266854bcefc73286868e27c882ee9

如果您不想指定任何字段,只需跳过insert @fields (value) values ('One'),('Two');语句即可;即传入一个空表。

答案 1 :(得分:0)

我创建了此程序,该程序删除重复的行但保留一个

`CREATE PROCEDURE [dbo].[DeleteDuplicateRows] 
 @TableName NVARCHAR(MAX) ,
 @FildesName NVARCHAR(MAX) 
 AS
 BEGIN

    DECLARE @sql NVARCHAR(MAX)

    set @sql='DELETE FROM '+@TableName +' WHERE Id IN (
    SELECT Id FROM (
        SELECT 
        Id
        ,ROW_NUMBER() OVER (PARTITION BY '+ @FildesName +' ORDER BY Id) AS [ItemNumber]
    FROM '+@TableName +
') a WHERE ItemNumber > 1 )'

EXEC sp_executesql @sql

END`

@TableName中-表的名称。 @FildesName中-双行的关键字段