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 bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Using an Input Parameter as a Table name 1

Status
Not open for further replies.

phbrady

Programmer
Oct 17, 2003
41
US
I am trying to use an input parameter as a table name in a stored proc. I am getting an error saying that the variable @dateid has not been declared.
Is there any way to use a table name that is dynamically created in the calling script and passed on to the sp as an input variable ?

CREATE PROCEDURE sp_ScoreCardsDrill1

@cocoid int,
@categoryid char (20),
@dateid char (20)

AS
SET NOCOUNT ON

IF @categoryid = 'NewClaims'

BEGIN
SELECT * FROM @dateid WHERE COCO_NO=@cocoid
END
GO

Thanks
 
I don't believe that you can use a variable directly for a table name, but you might be able to construct the query dynamically as follows:
Code:
CREATE PROCEDURE sp_ScoreCardsDrill1

@cocoid int,
@categoryid char(20),
@dateid char(20)

AS
  SET NOCOUNT ON

  DECLARE @query varchar(250)

  IF @categoryid = 'NewClaims'
  BEGIN
    SET @query = 'SELECT * FROM '+@dateid+' WHERE COCO_NO = '+CONVERT(varchar, @cocoid)
    EXEC sp_executesql @query
  END
GO

Hope this helps,
John
 
Thanks John, this is a great solution for my problem
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top