Home Forums SQL Server 7,2000 T-SQL Dynamic SQL issues with passing variables in stored procedure RE: Dynamic SQL issues with passing variables in stored procedure

  • r.hensbergen (1/16/2009)

    This way the code expects @ErrorReason to be a column name, to prevent this, replace ' + @ErrorReason + ' with ''' + @ErrorReason + '''

    Thanks Ronald, I replaced the variable the way you mentioned by adding two single quotes on both sides like this;

    CREATE PROCEDURE dbo.spWriteErrorRows

    @BatchID INT,

    @ErrorReason VARCHAR(200),

    @WhereStatement VARCHAR(200)

    AS

    EXEC('

    INSERT INTO dbo.ImportError

    (DataElementID, CenterCode, ValueType, ValueDate, [Value], ImportDate, BatchID, ErrorReason)

    SELECT

    DataElementID, CenterCode, ValueType, ValueDate, [Value], GetDate(), ' + @BatchID + ', ''' + @ErrorReason + '''

    FROM dbo.ImportAccess

    WHERE' + @WhereStatement)

    GO

    But now I get the OPTIMIZER LOCK HINTS error:

    Server: Msg 155, Level 15, State 1, Line 4

    [Microsoft][ODBC SQL Server Driver][SQL Server]'DataElementID' is not a recognized OPTIMIZER LOCK HINTS option.

    Failed to get the call stack!