正确的方式返回价值

时间:2014-06-24 04:17:48

标签: sql sql-server

我有一种情况,我想删除Members表中的成员,当且且只有该成员在MEMBERS_TRANSACTION表中没有事务。

我也想知道该成员是否有任何交易。目前,我将返回一个值为1的列,以指示该成员至少存在一个事务,或0以指示该成员没有事务并且在执行此查询时已被删除。我的查询如下:

IF EXISTS 
( 
    SELECT members_trans_id 
    FROM MEMBERS_TRANSACTION 
    WHERE member_link_id = 188
) 
    SELECT 1 
ELSE 
    DELETE FROM Members WHERE member_link_id = 188;
    SELECT 0

我关注的是ELSE块中的两行。我可以在SQL Server Management Studio中执行此查询而没有任何问题,但我想知道它是否正确以这种方式编写它。

我使用的是SQL Server 2008 R2。

谢谢。

3 个答案:

答案 0 :(得分:0)

左联盟是你的朋友而且非常快。要查看所有成员及其交易:

select m.Name, count(*) As TotalTransactions
from Member m
LEFT JOIN MEMBERS_TRANSACTION mt on mt.member_link_id=m.member_link_id
where mt.member_link_id is null
GROUP BY m.Name
ORDER BY m.Name

(只查找没有交易的那些,在结尾添加一个HAVING COUNT(*)= 0)

摧毁贪婪者:

delete m
from Member m
LEFT JOIN MEMBERS_TRANSACTION mt on mt.member_link_id=m.member_link_id
where mt.member_link_id is null

我假设你想为所有成员做这件事。显然,对于一个人在where子句中添加他们的ID。

答案 1 :(得分:0)

如果您加入或提供子查询,您将实现此目的。很高兴使用join。

在sqlserver 2008中,Merge statement介绍了在这种情况下哪个非常好。

当我们使用以下内容时,请阅读关于基本的好文章: -

left outer v/s not existnot in v/s not exist

在删除此查询之前始终使用选择查询

create table Members (member_link_id int , name varchar(50))
create table MEMBERS_TRANSACTION ( members_trans_id int , member_link_id int, name varchar(50))

insert into Members values(188,'abc'),(189,'abc1'),(190,'abc2'),(192,'abc3'),(193,'abc4')
insert into MEMBERS_TRANSACTION values(1,189,'abc'),(2,190,'abc1')

/*for select with left outer join to understand better*/
select * from Members m left outer join MEMBERS_TRANSACTION mt on m.member_link_id = mt.member_link_id

-/*1st approach*/
select * from Members m 
where not exists ( select members_trans_id from MEMBERS_TRANSACTION mt where m.member_link_id = mt.member_link_id )
and member_link_id = 188

select * from Members m 
where not exists ( select members_trans_id from MEMBERS_TRANSACTION mt where m.member_link_id = mt.member_link_id )
and member_link_id = 189

/*2nd approach with merge option, it is give error*/
MERGE Members AS m
USING (SELECT member_link_id FROM MEMBERS_TRANSACTION ) AS mt
ON mt.member_link_id = m.member_link_id
WHEN MATCHED THEN 
SELECT * from Members 
WHEN NOT MATCHED THEN
SELECT * from Members where m.member_link_id = 188

drop table member
drop table MEMBERS_TRANSACTION

答案 2 :(得分:0)

只需尝试删除并检查SQL Server返回的已修改行数:

DELETE FROM Members
WHERE member_link_id = 188 AND NOT EXISTS (
    SELECT *
    FROM MEMBERS_TRANSACTION 
    WHERE member_link_id = 188
) 

我建议在T-SQL中使用尽可能少的过程逻辑。 C#可以更好地处理逻辑。