如何正确地将查询结果发送到存储过程?

时间:2015-03-16 11:03:24

标签: sql-server

我有2张桌子。我想将表a中的行数与表b中的值进行比较:

select count(1) from table_a; -- returns 1500
select some_var from table_b; -- returns 1490

我想比较这些数字并相应地执行并在table c中写一行。 tabel_c是一种审计日志,通过存储过程填充:

create procedure dbo.audit_log (
  @query varchar(100)
, @result varchar(100) 
) as
insert into [table_c] (finished, query, result) 
values (getdate(), @query, @result)

我正在比较table_atable_b的值,如下所示:

select 
    case when (select count(1) from table_a) != (select row_count from table_b) 
         then 'Values do not match' else 'Values match'
    end

我的问题是如何将查询结果添加到审核日志(table_c)。我在尝试:

exec dbo.audit_log 'Compare values from 2 tables', (
    select 
        case when (select count(1) from table_a) != (select row_count from table_b)                  then 'Values do not match' else 'Values match' 
        end
    )

但是,这不起作用:Incorrect syntax near '('

问题审核日志中添加Compare values from 2 tablesValues do not match值的正确systax是什么?

2 个答案:

答案 0 :(得分:1)

declare @table_a as table (
id int
)
insert into @table_a values (1)

declare @table_b as table (
row_count int
)
insert into @table_b values (1)

declare @out varchar(max);

select @out = 
case when (select count(1) from @table_a) != (select row_count from @table_b) 
then 'Values do not match' else 'Values match'
end

exec dbo.audit_log 'Compare values from 2 tables', @out

这对你有用。请试试。

答案 1 :(得分:0)

接受我的答案:

declare @valueA int
      , @valueB int
      , @msg    varchar(50);

SELECT @valueA = a.value_a
     , @valueB = b.value_b
     , @msg  = case
       when value_a = b.value_b then 'values do match'
       else 'values do not match'
       end
FROM
( select count(*)  value_a from table_a) a ,
( select row_count value_b from table_b) b;

select @valueA va, @valueB vb, @msg msg;

if (@valueA <> @valueB)
  exec dbo.audit_log @msg, @valueA, @valueB;