a simple question

  • Hello

    i want to write a store procedure which takes a tablename from adatabase and give me the Last ID.(ID is one of my fields)

    i wrote this:

    create PROCEDURE dbo.GetLastID2(@Table_Name nvarchar(25))

    AS

    begin

    select top 1 id from @Table_Name order by id desc

    END

    GO

    but an erroe is occured:

    Must declare the table variable "@Table_Name ".

    ????

  • Try this

    Create Procedure dbo.GetLastID2(@Table_Name varchar(25))

    As

    Begin

    DECLARE @sqlString varchar(100)

    SET @sqlString='select top 1 id from '+@Table_Name+' order by id desc'

    EXECUTE sp_executesql @sqlString

    END

    GO

    [font="Verdana"]Thanks
    Chandra Mohan[/font]

  • Thank u very much but i have 3 questions:

    why when i write:

    1) EXECUTE GetLastID2 @sqlString

    it doesnt work ?

    2) what should i write instead of @sqlString when i want to execute this

    and

    3) where i should write the table _name?

    thank you verymuch

  • Make sure you read this

    www.sommarskog.se/dynamic_sql.html


    Madhivanan

    Failing to plan is Planning to fail

Viewing 4 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply