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

  • henkvisser (1/16/2009)


    I'm trying to use the stored procedure below in SQL Server 2000, but I get the following error;

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

    [Microsoft][ODBC SQL Server Driver][SQL Server]Line 4: Incorrect syntax near 'much'.

    Failed to get the call stack!

    I know there difficulties passing tablenames but this is clearly not a tablename.

    Var values used:

    @BatchID = 461

    @ErrorReason = 'DataElementID too much characters (>3)'

    @WhereStatement = 'LEN(DataElementID) > 3'

    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

    Obviously it can't handle the @ErrorReason variable. Is there any way to fix this?

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

    Ronald HensbergenHelp us, help yourself... Post data so we can read and use it: http://www.sqlservercentral.com/articles/Best+Practices/61537/-------------------------------------------------------------------------2+2=5 for significant large values of 2