【问题标题】:Checking for existance of data from a parameter list检查参数列表中的数据是否存在
【发布时间】:2020-01-25 19:17:40
【问题描述】:

我目前正在从事一个让我很困惑的项目,因为我没有做太多的存储过程设计。我有一项任务,当输入用户时,他们可以与一个或多个组相关联。当将存储过程调用为@GroupList =“'Group1','Group2','Group3'”时,我将组列表作为参数传递。可以有任意数量的组。如果其中一个组不存在,则添加新用户的调用应该会失败。我正在尝试使用以下代码在使用现有组的 ID 填充临时表之前检查它是否存在。我的问题是它总是失败。我已经尝试了我能想到的一切,所以我转向比我更熟练的人。提前致谢。对我来说失败的是 if exists 语句。

Declare @GroupList varchar(100), @return int, @sql varchar(1000)
if @GroupList is not null
begin
if (object_id ('tempdb..#TempGroupList') is not null) drop table #TempGroupList
Create Table #TempGroupList
(
GroupID int,
PlayerID int
)
if exists (select * from Group_new where GroupName in (' + @GroupList + '))
    begin
    --lets populate our temp table
        set @SQL = 'insert into #TempGroupList (GroupID) select GroupID from Group_New where GroupName in (' + @GroupList + ')'
        exec(@sql)
    end
else
set @return = 1
select @return
print 'Stop, one of the Group names you entered does not exist'
Return
end

【问题讨论】:

    标签: sql sql-server tsql stored-procedures sql-server-2016


    【解决方案1】:

    我会将输入分开,进行检查,然后插入:

    create procedure . . . (
        Declare @GroupList varchar(100),
        @return int, @sql varchar(1000)
    ) as
    begin
        declare table @groups (grp varchar(255));
    
        insert @groups (grp)
            select ltrim(rtrim(value))
            from string_split(@grouplist, ',');
    
        if not exists (select 1
                       from @groups g
                       where not exists (select 1 group_new gn where gn.groupname = g.groupname)
                      )
        begin
            . . .  whatever you want to do here
        end;
        else begin
            print 'Stop, one of the Group names you entered does not 
        end;
    end;
    

    填充存储过程中定义的临时表并没有多大作用,因为在存储过程返回时临时表被删除。但是您可以在if 之后的 then 部分中添加任何您想要的逻辑。

    【讨论】:

    • 你是上帝派来的!谢谢你,它比我试图做的要干净得多。它按预期工作!
    猜你喜欢
    • 2013-07-16
    • 1970-01-01
    • 1970-01-01
    • 2012-01-26
    • 2018-08-26
    • 2012-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多