Sunday, February 19, 2012

How to access tables from a dynamic

I have a procedure that takes database name and queries some tables in the database specified. I am trying to access tables like this:

SELECT COUNT(id) FROM @.dbname..sysobjects WHERE type='U'

How can I access the tables while the database name is in a variable.

Thanx.I have a procedure that takes database name and queries some tables in the database specified. I am trying to access tables like this:

SELECT COUNT(id) FROM @.dbname..sysobjects WHERE type='U'

How can I access the tables while the database name is in a variable.

Thanx.

You can do it with an exec call:

EXEC('SELECT COUNT(id) FROM ' + @.dbname + '..sysobjects WHERE type = ''U''')

The U value needs to be surrounded by 2 pairs of single quotes, because it is a string within a string.|||Hi, Thanx.

No comments:

Post a Comment