我正在尝试编写存储过程测试用例以进行功能检查。我需要检查更新操作是否完成了插入和/或删除操作。我尝试使用BINARY_CHECKSUM(*)进行更新,但我如何知道通过结果集进行更新操作的行数是插入还是删除表。
我只是在使用 MS SQL Server 2005
感谢您。
我正在尝试编写存储过程测试用例以进行功能检查。我需要检查更新操作是否完成了插入和/或删除操作。我尝试使用BINARY_CHECKSUM(*)进行更新,但我如何知道通过结果集进行更新操作的行数是插入还是删除表。
我只是在使用 MS SQL Server 2005
感谢您。
引用:
我遵循的是将数据插入到 temp 中。表和实际表然后对其中一个执行操作并...检查过程的功能。
如果您的最终问题可以描述为比较两个表中的实际数据和预期数据,那么您可以尝试下一种方法 - 比较 usingexcept
子句:
create table [tb_source] (id int primary key identity(1,1), value varchar(50));
create table [tb_dest] (id int primary key, value varchar(50));
insert into [tb_source] (value) values ('a');
insert into [tb_source] (value) values ('b');
insert into [tb_source] (value) values ('c');
-- tables are equal
insert into [tb_dest] select * from [tb_source];
-- one row inserted
insert [tb_dest] (id, value) values (4, 'd');
-- one row deleted
delete from [tb_dest] where id = 1;
-- one row updated
update [tb_dest] set value = 'b_' where id = 2;
-- answering the question "how many number of rows with update operation through result"
with [raw] as (
(select *, 'deleted' [operation] from [tb_source]
except
select *, 'deleted' from [tb_dest])
union all
(select *, 'inserted' from [tb_dest]
except
select *, 'inserted' from [tb_source])),
[updates] as (
select id
from [raw]
group by id
having count(*) > 1),
[results] as (
select * from [raw] where id not in (select id from [updates])
union all
select id, value, 'updated' from [raw] where id in (select id from [updates]))
select [operation], count(distinct id)
from [results]
group by [operation]
order by count(*) desc
结果:
operation count
---------------------------------
updated 1
deleted 1
inserted 1
如果不久之后:
作为一个选项,您可以尝试使用触发器来找出操作的类型:
ALTER TRIGGER [dbo].[MyTrigger]
ON [dbo].[MyTable]
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
SET NOCOUNT ON;
declare
@i int = (select count(*) from (select top (1) * from inserted) as i),
@d int = (select count(*) from (select top (1) * from deleted) as d),
@type varchar(20);
if @i = 1 and @d = 1 set @type = 'update'
else if @i = 1 and @d = 0 set @type = 'insert'
else if @i = 0 and @d = 1 set @type = 'delete'
else set @type = 'empty';
if @type = 'insert'
begin
-- YOUR CODE HERE
end
if @type = 'delete'
begin
-- YOUR CODE HERE
end
if @type = 'update'
begin
-- YOUR CODE HERE
end
if @type = 'empty'
begin
-- YOUR CODE HERE
end
END