Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

I am trying to insert a record into 3

Status
Not open for further replies.

johnrg1

Programmer
Jan 24, 2003
38
GB
I am trying to insert a record into a table that was created on the fly. The table is created with errors, and when i check it, all the columns are of the correct data types. I am using the code

ALTER PROCEDURE InsertStudenttoClass
(
@tableName varchar(10),
@StudentID int
)
AS
DECLARE @myStr varchar(1500)

SELECT @mySTR= 'INSERT INTO [dbo].['+@tablename+'] (StudentID) VALUES (@StudentID)'

EXEC (@myStr)


The error messages is telling me to declare the @student variable.

Any ideas?
 
Your problem is your @studentID. You need the actual value passed in for your insert. Try this:

ALTER PROCEDURE InsertStudenttoClass
(
@tableName varchar(10),
@StudentID int
)

AS
DECLARE @myStr varchar(1500)

select @tableName = 'test'
select @StudentID = 1
SELECT @mySTR= 'INSERT INTO [dbo].['+@tablename+'] (StudentID) VALUES (' + cast(@StudentID as varchar(10)) + ')'

exec (@myStr)

Hope this helps.
 
Hi,

Change ur Select @myStr Line like this

SELECT @mySTR= 'INSERT INTO [dbo].['+@tablename+'] (StudentID) VALUES (' + @StudentID + ')'

EXEC (@myStr)


Sunil
 
When you execute the query dynamically, the scope changes and the variable is not available in the execute scope. The value of the parameter must be evaluated before executing the SQL statement. Modify the SELECT statemetn as follows.

SELECT @mySTR= 'INSERT INTO [dbo].['+@tablename+'] (StudentID) VALUES (' + str(@StudentID) + ')'

EXEC (@myStr) If you want to get the best answer for your question read faq183-874 and thread183-468158.
Terry L. Broadbent - DBA
SQL Server Page:
 
I do not care what anyone says, you guys ARE the best!

Thank you very much, it all works perfectly now.

John
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top