Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

sql server 2008 - Stored procedure with table name as parameter

I have a stored procedure, and I would like to assign the number of rows of that table to a variable and later use that variable.

I am calling the procedure like:

EXEC TEST.dbo.myProc nameOfTable

The procedure is something like:

CREATE PROCEDURE myProc @table_name varchar(1024) AS
BEGIN
    DECLARE  @Nval INT
    /*  SOME INSTRUCTIONS */

    SELECT   @Nval  = COUNT(*) FROM @table_name 
END 

When executing I am getting an error:

Msg 156, Level 15, State 1, Procedure nLQ, Line 57
Incorrect syntax near the keyword 'FROM'.

How would I assign the variable @Nval?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can't parameterise a table name like that, FROM @table_name. Only way is to execute dynamic TSQL.

Before you do that, read: The Curse and Blessings of Dynamic SQL


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...