I want to write sample procedure to count the records present in specific tables, here i will fetch the table name s from the text file. Fo this i just write sample procedure to fetch th table names from text file and storing in tem table but while i am assigning and passing the table name i am unable to do it can any one suggest how to do it by simple example
1 Answer
You can build dynamic sql using table name parameter and execte it using EXEC as shown below.
Create procedure Proc1
@TableName varchar(MAX)
as
..
...
DECLARE @sqltxt varchar(1000)
select @sqltxt = 'select count(*) from ' + quotename(@TableName)
exec (@sqltxt)
...
...
4 Comments
Thomas
If you are going to do this, you should use
Quotename: Set @sqltxt = 'Select ... From ' + Quotename( @TableName ).Kashif
exec (@sql) should be exec (@sqltxt)
Thomas
+1 for the corrected version, although the actual correct answer should be "don't do this".
Anil Soman
@Thomas - Ya.That's why I had asked a query / feature request in meta for marking a comment as an answer. If they would have enabled this feature, then your query could have been marked as answer! meta.stackexchange.com/questions/77900/…