Sunday, February 19, 2012

How to get field value from a dynamic table in stored procedure

In my stored procedure,I want get some fields' value from a dynamic
table,something look like below:
PROCEDURE GetFileds
(
@.Field1 INT,
@.Field2 VARCHAR(255),
@.Table VARCHAR(255)
)
AS
--I want to get two fields from table which's name was passed by
paramerter.
SELECT
@.Field1 = FIELD1,
@.Field2 = FIELD2
FROM
@.Table
--Show @.Filed1 and @.Field2's Value
PRINT CONVERT(VARCHAR(255), @.Field1)
PRINT @.Field2
How to do that?I use EXECUTE() function,but the table name can't be
dynamic.debussy@.gmail.com wrote:
> In my stored procedure,I want get some fields' value from a dynamic
> table,something look like below:
> PROCEDURE GetFileds
> (
> @.Field1 INT,
> @.Field2 VARCHAR(255),
> @.Table VARCHAR(255)
> )
> AS
> --I want to get two fields from table which's name was passed by
> paramerter.
> SELECT
> @.Field1 = FIELD1,
> @.Field2 = FIELD2
> FROM
> @.Table
> --Show @.Filed1 and @.Field2's Value
> PRINT CONVERT(VARCHAR(255), @.Field1)
> PRINT @.Field2
> How to do that?I use EXECUTE() function,but the table name can't be
> dynamic.
My suggestion wold be not to do this. But read this article:
http://www.sommarskog.se/dynamic_sql.html
Microsoft MVP - ASP/ASP.NET
Please reply to the newsgroup. This email account is my spam trap so I
don't check it very often. If you must reply off-line, then remove the
"NO SPAM"|||(debussy@.gmail.com) writes:
> In my stored procedure,I want get some fields' value from a dynamic
> table,something look like below:
> PROCEDURE GetFileds
> (
> @.Field1 INT,
> @.Field2 VARCHAR(255),
> @.Table VARCHAR(255)
> )
> AS
> --I want to get two fields from table which's name was passed by
> paramerter.
> SELECT
> @.Field1 = FIELD1,
> @.Field2 = FIELD2
> FROM
> @.Table
> --Show @.Filed1 and @.Field2's Value
> PRINT CONVERT(VARCHAR(255), @.Field1)
> PRINT @.Field2
> How to do that?I use EXECUTE() function,but the table name can't be
> dynamic.
A counter-question, why? If this is how you want to program SQL, forget
about stored procedures and send the queries from the client. That will
make your life easier.
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp

No comments:

Post a Comment