0

I have something like this.

declare @insertQuery nvarchar(max)

declare @ifQuery nvarchar(max)

SET @insertQuery='...'

SET @ifQuery='if not exists(select Id from '+@DbName+'.[dbo].[tbl_TestHere] where Id='+@id+')'

  BEGIN
    Exec sp_executesql @insertQuery
END

I need to execute dynamic query @insertQuery if "if not exists(...)" returns true..But i couldn't find right solution for this. Thanks in advance

pavel
  • 26,538
  • 10
  • 45
  • 61
Dalls
  • 3
  • 4

1 Answers1

0

Just combine to queries together.

SET @FinalQuery NVARCHAR(MAX) = @ifQuery + @insertQuery;
EXEC (@FinalQuery);

Of course, you need to check if combined query is valid. Surround @insertQuery with BEGIN and END if needed.

If above combination is not valid for you, please check How to get sp_executesql result into a variable?.

Community
  • 1
  • 1
qxg
  • 6,955
  • 1
  • 28
  • 36