2
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

BALU K B
  • 135
  • 12
  • sorry i cant get it. – BALU K B Aug 13 '15 at 10:14
  • See [SQL “if exists…” dynamic query][1] or [TSQL - Trying to use variable with IF EXISTS() Function for simple SP][2] [1]: http://stackoverflow.com/questions/27710260/sql-if-exists-dynamic-query [2]: http://stackoverflow.com/questions/14073842/tsql-trying-to-use-variable-with-if-exists-function-for-simple-sp – Esty Aug 13 '15 at 10:17

2 Answers2

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)
Raj Kamuni
  • 388
  • 2
  • 12
1

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
Praveen
  • 8,945
  • 4
  • 31
  • 49