Click to See Complete Forum and Search --> : stored procedure error


Sairan
November 7th, 2006, 02:41 AM
hello,
i'm creating a stored procedure that will give me the structure of whichever table name i provide it with.

the stored procedure i'm using is

CREATE PROCEDURE Describe_table (@table_name varchar) AS
SET NOCOUNT OFF
Select * from table_name
GO

the code i'm using to run this procedure is

cmd=new SqlCommand("Describe_table",conn);
cmd.CommandType=CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@table_name",SqlDbType.NVarChar,0, ParameterDirection.Input, false, 0,0,"table_name", DataRowVersion.Default, comboBox1.Text));
cmd.UpdatedRowSource=UpdateRowSource.OutputParameters;
cmd.ExecuteNonQuery();

i get the following messsage at runtime

invalid object name "table_name"

i understand that the stored procedure treats the 'table_name' in the SELECT clause as a constant name.
how can i make it a variable

i've tried modifying the procedure

CREATE PROCEDURE Describe_table (@table_name varchar) AS
SET NOCOUNT OFF
Select * from @table_name
GO

but this gives me the error of invalid syntax near 'table_name'

plz help me quick
thanks

Alsvha
November 7th, 2006, 04:11 PM
Change the content of your stored procedure to a string which you then can execute in your stored procedure.
Then you can use variables as for instance table name:

For instance something along this line:


declare @sqlContent nvarchar(2000)
Set @sqlContent = 'SELECT * FROM ' + @table_name
exec(@sqlContent)

hspc
November 10th, 2006, 10:10 AM
If you just want to get column names then use :
Select top 0 * ........
instead of
Select * ........

the second one will get all the data from the table which you don't need in this case.