如果存在条件,如何执行子查询?

时间:2015-08-13 10:04:12

标签: sql subquery

declare @qry varchar(100)
declare @cnt int
set @qry = ' where '

if exists( select * from  ARTICLE_MANAGE +@qry+ article_id=65)
BEGIN
select top 1* from  ARTICLE_MANAGE order by article_id desc
END
ELSE
BEGIN
select * from  ARTICLE_MANAGE order by article_id desc
END

这是查询。 '@ qry'由我们传递给查询的内容改变

2 个答案:

答案 0 :(得分:2)

DECLARE @qry VARCHAR(100);
DECLARE @cnt INT;
set @qry = ' where '
DECLARE @ExeQuery VARCHAR(MAX);
SET @ExeQuery='if exists( select * from  ARTICLE_MANAGE '+@qry+' article_id=65)
BEGIN
select top 1* from  ARTICLE_MANAGE order by article_id desc
END
ELSE
BEGIN
select * from  ARTICLE_MANAGE order by article_id desc
END'
 EXEC(@ExeQuery)

答案 1 :(得分:1)

您只需dynamic sql EXISTS建立subqueryEXISTS限制。

您可以使用count(*)

declare @qry varchar(100) declare @cnt int set @qry = ' where ' declare @sql_qry nvarchar(1000) set @sql_qry = 'select @Cnt = COUNT(*) from ARTICLE_MANAGE' + @qry + 'article_id=65' DECLARE @Count AS INT EXEC sp_executesql @Query, N'@Cnt INT OUTPUT', @Cnt=@Count OUTPUT if exists(@Count > 0) BEGIN select top 1* from ARTICLE_MANAGE order by article_id desc END ELSE BEGIN select * from ARTICLE_MANAGE order by article_id desc END 功能
ID | volunteerID | hoursWorked