SQL - 查找匹配的字符串,如果未找到则停止

时间:2016-08-02 10:38:47

标签: sql sql-server stored-procedures

我正在尝试编写存储过程,这涉及将表中的字符串列表与另一个表中的列进行匹配。如果与表相比,即使列中的一个文本字符串错误,该过程也会中断。

enter image description here

4 个答案:

答案 0 :(得分:0)

我会使用not exists执行此操作:

if (exists (select 1
            from tomatch m
            where not exists (select 1 from list l where l.template = m.template)
           )
   )
    return 'Bad'  -- or whatever you want to return
else return 'Good';

如果您在list(template)上有索引,那么我认为这是解决问题的最快方法。

答案 1 :(得分:0)

使用这个简单的规则:

IF EXISTS(SELECT * FROM TableToMatch T2
          WHERE NOT EXISTS(SELECT * FROM ListTable T1 WHERE T1.Template=T2.Template))
    THROW;

如果您想更精确,请返回消息:

IF EXISTS(SELECT * FROM TableToMatch T2
          WHERE NOT EXISTS(SELECT * FROM ListTable T1 WHERE T1.Template=T2.Template))
    THROW 50000, 'Procedure is too crazy to finish', 0

如果您想要对称匹配,可以使用FULL OUTER JOIN:

IF EXISTS(
        SELECT *
        FROM TableToMatch T1
        FULL JOIN ListTable T2 ON T1.Template=T2.Template
        WHERE T1.Template IS NULL OR T2.Template IS NULL)
    THROW 50000, 'Procedure is too crazy to finish', 0

答案 2 :(得分:0)

您需要检查两个方向,以确保处理所有差异:

if exists(
select 1
from List
where not exists (select 1
                  from Temp
                  where List.CUSTID = Temp.TEMPID and List.Template = Temp.template)
union
select 1
from Temp
where not exists (select 1
                  from List
                  where List.CUSTID = Temp.TEMPID and List.Template = Temp.template))
return 0;
else return 1;

答案 3 :(得分:-1)

尝试运行此查询:

DECLARE @CountOfNonMatchRecords INT
SELECT 
@CountOfNonMatchRecords = COUNT(T.Template)
FROM <TableToMatch> T
LEFT JOIN 
<ListTable> L ON L.Template = T.Template
WHERE L.Template IS NULL

IF @CountOfNonMatchRecords > 0 THEN
BEGIN
--Break your procedure
END