Tuesday 24 January 2017

SQL Dynamic table’s name in SELECT COUNT(*),TOP 1, MAX etc..

Hi All, here a easy lwebcode's sql script, to make a SELECT COUNT(*), or other sql statements wich return only 1 result (SELECT TOP 1, SELECT MAX, etc..) with dynamic tables name and put in a parameter o variable, 
It works well in All Sql Server versions, from MS SQL Server 2000 to last SQL Server 2016 

--LWEBCODE SQL SCRIPT Dynamic table's name
Declare @tableName varchar(100),
@tableCount int,
@sql nvarchar(100)
Set @tableName = 'Products'
Set @sql = N'Select @tableCount = Count(*) from ' + @tableName
exec sp_executesql @sql, N'@tableCount int output', @tableCount output
Select @tableCount

No comments:

Post a Comment