【问题标题】:How to execute sub query in if exists condition?如果存在条件下如何执行子查询?
【发布时间】:2015-08-13 10:04:11
【问题描述】:
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' 被我们传递给查询的内容所改变

【问题讨论】:

标签: sql subquery


【解决方案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)

【讨论】:

  • 它工作正常..这是我正在寻找的确切解决方案..谢谢 RAJ.. :)
【解决方案2】:

在这里,您正在将 dynamic sqlEXISTS 限制为仅 subquery

count(*) 可以拥有EXISTS 的功能

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

【讨论】:

  • 感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 2012-02-22
  • 2020-08-29
  • 1970-01-01
  • 2011-09-27
  • 2015-09-25
  • 1970-01-01
  • 2019-09-12
  • 1970-01-01
相关资源
最近更新 更多