Sql server 2008 当一个表中没有数据时,需要在连接两个表时引发异常

Sql server 2008 当一个表中没有数据时,需要在连接两个表时引发异常,sql-server-2008,sql-server-2008-r2,Sql Server 2008,Sql Server 2008 R2,假设有两个表test1和test2,我使用联接从这两个表中选择值 我的要求是:当我连接两个表时,如果test1中有数据,但是test2中没有相应的数据,那么查询应该抛出异常 DECLARE @count INT SELECT @count = COUNT(*) FROM test1 t1 LEFT JOIN test2 t2 ON t1.t1_join_col = t2.t2_join_col WHERE t2.t2_join_col IS NULL -- find w

假设有两个表
test1
test2
,我使用联接从这两个表中选择值

我的要求是:当我连接两个表时,如果
test1
中有数据,但是
test2
中没有相应的数据,那么查询应该抛出异常

DECLARE @count INT

SELECT 
   @count = COUNT(*)
FROM
  test1 t1
LEFT JOIN test2 t2 
  ON t1.t1_join_col = t2.t2_join_col
WHERE 
  t2.t2_join_col IS NULL -- find where we have test1 data but not test2 data

-- Check if I need to raise an error
IF @count <> 0 
    RAISERROR (N'<<%7.3s>>', -- Message text.
           10, -- Severity,
           1, -- State,
           N'abcde'); -- First argument supplies the string.
    -- The message text returned is: <<    abc>>.
如何才能做到这一点?

您需要

执行左连接并选择右侧为空的位置。如果计数>0,则抛出异常

DECLARE @count INT

SELECT 
   @count = COUNT(*)
FROM
  test1 t1
LEFT JOIN test2 t2 
  ON t1.t1_join_col = t2.t2_join_col
WHERE 
  t2.t2_join_col IS NULL -- find where we have test1 data but not test2 data

-- Check if I need to raise an error
IF @count <> 0 
    RAISERROR (N'<<%7.3s>>', -- Message text.
           10, -- Severity,
           1, -- State,
           N'abcde'); -- First argument supplies the string.
    -- The message text returned is: <<    abc>>.
您可以随时将结果放入临时表中,并对其进行计数,如果希望只执行一次查询,也可以将其返回。

您需要

执行左连接并选择右侧为空的位置。如果计数>0,则抛出异常

DECLARE @count INT

SELECT 
   @count = COUNT(*)
FROM
  test1 t1
LEFT JOIN test2 t2 
  ON t1.t1_join_col = t2.t2_join_col
WHERE 
  t2.t2_join_col IS NULL -- find where we have test1 data but not test2 data

-- Check if I need to raise an error
IF @count <> 0 
    RAISERROR (N'<<%7.3s>>', -- Message text.
           10, -- Severity,
           1, -- State,
           N'abcde'); -- First argument supplies the string.
    -- The message text returned is: <<    abc>>.
您可以将结果放入一个临时表中,并对其进行计数,如果您希望只执行一次查询,则也可以将其返回