SQL Server Performance

Table name in dynamic sql query

Discussion in 'SQL Server 2005 General DBA Questions' started by ismailadar, Mar 6, 2010.

  1. ismailadar New Member

    Hi all,
    I wanna create a stored proc that returns all values in a table but the table name should be parametre of stored proc
    Create Procedure tableProc( @tblName varchar(20) = 'tbl_Products')
    As
    Begin
    Select * from @tblName

    End
    How can i achieve this?
  2. Subhash_Chandra New Member

    Using the dynamic query as below:Create
    Procedure tableProc( @tblName varchar(20) = 'tbl_Products')As
    Begin
    declare
    @strSQL as varchar(1000)set
    @strSQL = 'Select * from ' + @tblName exec
    (@strSQL)End
    exec
    tableProc 'mytable1'
    Regards,
    Subhash Chandra,
    http://SQLReality.com/blog/
  3. ismailadar New Member

    thnaks for your reply
  4. Madhivanan Moderator

  5. ismailadar New Member

    hi again,
    Thats all work but i could not pass a datetime parametre to procedure when i try it give an error that says "incorrect systax near the 5" than when i print the datetime parametre i see 5 Dec 2009 do you have any idea to solve this?
  6. Madhivanan Moderator

    You need to inlcude single quotes. Post the full code you used
  7. ismailadar New Member

    hi here is my code:
    This my proc .it has two parametresCreate
    Procedure getStatisticsArsin10dk(@tblName varchar(20),@date datetime)As
    Begin
    declare @startTime datetime
    declare
    @endTime datetimeset
    @starttime=dateadd(year,-1,getdate())set
    @endTime=dateadd(hour,1,@starttime)declare
    @strSQL as varchar(1000)set @strSQL = 'Select * from ' + @tblName +'where InsertedTime between '+@starttime+ ' and '+@endTime exec
    (@strSQL)End
    ---------------------Declare @date datetime
    Declare
    @tblname varchar(50)Set @date=dateadd(year,-1,getdate()) SELECT @tblname=[TableName]
    FROM [DB].[dbo].[Tbl_TableIndex]where [Year]=Year(@date) and month(@date) between [StartMonth] and [EndMonth] getStat @tblname
    ,@date
  8. Madhivanan Moderator

    set @strSQL = 'Select * from ' + @tblName +'where InsertedTime between '+@starttime+ ' and '+@endTime
    should be
    set @strSQL = 'Select * from ' + @tblName +'where InsertedTime between '''+cast(@starttime as varchar(50))+ ''' and '''+cast(@endTime as varchar(50))+''''
  9. ismailadar New Member

    thanx a lot it solved problem...
  10. moh_hassan20 New Member

    it's better to use sp_executesql instead of exec, for better performance

Share This Page