How to execute sub query in if exists condition?

左心房为你撑大大i 提交于 2019-12-07 23:58:05

问题


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

This is the query. '@qry' is changed by what we passed to the query


回答1:


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)



回答2:


Here you are building a dynamic sql and EXISTS limits to only subquery.

You can have the functionality of EXISTS with 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


来源:https://stackoverflow.com/questions/31985175/how-to-execute-sub-query-in-if-exists-condition

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!