SQL "if exists..." dynamic query
Try this:
DECLARE @Query NVARCHAR(1000) = 'SELECT @C = COUNT(*) FROM dbo.MyTable'
DECLARE @Count AS INT
EXEC sp_executesql @Query, N'@C INT OUTPUT', @C=@Count OUTPUT
IF (@Count > 0)
BEGIN
END
Try Executing the Dynamic query
and use @@RowCount
to find the existence of rows.
DECLARE @Query NVARCHAR(1000) = 'SELECT * FROM [dbo].[Mytable]',
@rowcnt INT
EXEC Sp_executesql @query
SELECT @rowcnt = @@ROWCOUNT
IF @rowcnt > 0
BEGIN
PRINT 'row present'
END
I know this answer is too late. but, I'm leaving this here to help someone else to use IF EXISTS
with a dynamic query.
This is how you should do it with dynamic queries.
DECLARE @Query VARCHAR(MAX)
SET @Query = 'SELECT * FROM [dbo].[MyTable]'
SET @Query = 'IF EXISTS (' + @Query + ')
BEGIN
-- do something
print ''1''
END
ELSE
BEGIN
-- do something else
print ''0''
END
'
exec (@Query)
Hope this helped someone. Vote if it did :)