I think this way is best:
DECLARE
@Cnt int,
@SQL nvarchar(max),
@batch sysname,
@Identifier varchar(30)
-- set @batch and @Identifier
SET @SQL = 'SELECT @Cnt = Count(*) FROM ' + @batch
+ ' WHERE Identifier = @Identifier'
EXEC sp_executesql @SQL, N'@Cnt int OUT, @Identifier varchar(30)',
@Cnt OUT, @Identifier
IF @Cnt = 0 BEGIN
--do something
END
ELSE BEGIN
--do something else
END
Though if you only care whether it's 0 or not, then you should do this instead, which can stop after finding only one row, instead of having to count them all:
DECLARE
@HasRows bit,
@SQL nvarchar(max),
@batch sysname,
@Identifier varchar(30)
-- set @batch and @Identifier
SET @SQL = 'SET @HasRows = CASE WHEN EXISTS (SELECT 1 FROM '
+ @batch + ' WHERE Identifier = @Identifier) THEN 1 ELSE 0 END'
EXEC sp_executesql @SQL, N'@HasRows bit OUT, @Identifier varchar(30)',
@HasRows OUT, @Identifier
IF @HasRows = 0 BEGIN
--do something
END
ELSE BEGIN
--do something else
END
However, if there's any way you can avoid using dynamic SQL and changing table names, that would be best. Then it is a simple query:
IF NOT EXISTS (SELECT 1 FROM TableName WHERE Identifier = @Identifier) BEGIN
-- do something
END