sp_executesql

  • Hi,

    I'm trying to explore about sp_exectesql and the below query is showing the syntax error at '+mytable+'.

    Please advice..

    DECLARE @TblName varchar(50)

    DECLARE @ColValue int

    set @ColValue=30

    set @tblName='MyTable'

    execute sp_executesql N'Select * from '+ @Mytable + ' where somecol = @ColVal' , '@ColVal int', @ColValue;

  • DECLARE @TblName varchar(50)

    DECLARE @ColValue int

    set @ColValue=30

    set @tblName='MyTable'

    execute sp_executesql N'Select * from '+ QUOTENAME(@tblName) + ' where somecol = @ColVal' , '@ColVal int', @ColValue;


    Forever trying to learn
    My blog - http://www.cadavre.co.uk/
    For better, quicker answers on T-SQL questions, click on the following...http://www.sqlservercentral.com/articles/Best+Practices/61537/
    For better, quicker answers on SQL Server performance related questions, click on the following...http://www.sqlservercentral.com/articles/SQLServerCentral/66909/

  • You have to write the job like this:

    DECLARE @tblName nvarchar(50)

    DECLARE @sql nvarchar(200)

    set @tblName='T1'

    SET @sql = N'Select * from '+quotename(@tblName)

    execute sp_executesql @sql

    --The confidence is a premise, the courage is a motive, the perseverance is assurance!
    http://www.cnblogs.com/huyong/[/url]

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

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