Login or Sign Up to become a member!
LessThanDot Sit Logo

LessThanDot

Community Wiki

Less Than Dot is a community of passionate IT professionals and enthusiasts dedicated to sharing technical knowledge, experience, and assistance. Inside you will find reference materials, interesting technical discussions, and expert tips and commentary. Once you register for an account you will have immediate access to the forums and all past articles and commentaries.

LTD Social Sitings

Lessthandot twitter Lessthandot Linkedin Lessthandot friendfeed Lessthandot facebook Lessthandot rss

Note: Watch for social icons on posts by your favorite authors to follow their postings on these and other social sites.

Navigation

Google Ads

Use sp executesql Or EXEC To Get The Count For Dynamic Table Names

From Wiki

Jump to: navigation, search

You need the row count for a table but this table could change every day or change based on which user executes the stored procedure There is no point in creating dozens of stored procedures, all this can be done by using exec (sql) or sp_executesql Of course sp_executesql is much better and if you run the statements below you will also see that it's execution plan is only 29.04 percent relative to the batch
So let's get started.

  1. USE pubs
  2. GO
  3.  
  4. --sp_executesql
  5. DECLARE @chvTableName VARCHAR(100),
  6. @intTableCount INT,
  7. @chvSQL NVARCHAR(100)
  8.  
  9. SELECT @chvTableName = 'Authors'
  10. SELECT @chvSQL = N'SELECT @intTableCount = COUNT(*) FROM ' + @chvTableName
  11.  
  12. EXEC sp_executesql @chvSQL, N'@intTableCount INT OUTPUT', @intTableCount OUTPUT
  13.  
  14. SELECT @intTableCount
  15. GO
  16.  
  17.  
  18. --EXEC (SQL)
  19. DECLARE @chvTableName VARCHAR(100),
  20. @intTableCount INT,
  21. @chvSQL NVARCHAR(100)
  22.  
  23.  
  24. CREATE TABLE #temp (Totalcount INT)
  25. SELECT @chvTableName = 'Authors'
  26. SELECT @chvSQL = 'Insert into #temp Select Count(*) from ' + @chvTableName
  27.  
  28. EXEC( @chvSQL)
  29.  
  30. SELECT @intTableCount = Totalcount from #temp
  31.  
  32. SELECT @intTableCount
  33.  
  34. DROP TABLE #temp


First Hit CTRL + K (this will show the execution plan) , then highlight the complete code, hit F5 and look at the Execution Plan tab As you can see sp_executesql is more than twice as efficient as exec (SQL)





Contributed by: --SQLDenis 13:19, 5 August 2008 (GMT)

Part of SQL Server Programming Hacks

Section Handy tricks

562 Rating: 2.7/5 (25 votes cast)