如何在存在条件下执行子查询?
How to execute sub query in if exists condition?
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' 被我们传递给查询的内容改变了
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)
您在这里构建了一个 dynamic sql
和 EXISTS
限制,仅 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
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' 被我们传递给查询的内容改变了
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)
您在这里构建了一个 dynamic sql
和 EXISTS
限制,仅 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