executing dynamic sql string

  • hi (me again)

    i'm trying to get a proc to execute by passing in a dynamic sql string.

    this works...

    exec [MediaCreateCustomerDataSet] @accountId, @yr, @stockGroup, @stockCode, @stockDescription

    but this doesn't (error: The name '[MediaCreateCustomerDataSet] @accountId, @yr, @stockGroup, @stockCode, @stockDescription' is not a valid identifier.)...

    set @sqlStr = @dataSet + ' @accountId, @yr, @stockGroup, @stockCode, @stockDescription'

    exec @sqlStr

    i also tried (error: Incorrect syntax near ',')...

    set @sqlStr = @dataSet + ' ' + @accountId, @yr, @stockGroup, @stockCode, @stockDescription

    exec @sqlStr

    thanks

  • Why the square brackets around [MediaCreateCustomerDataSet] ?

    They aren't generally needed unless you're using a SQL Server reserved word or have spaces in the name. Have you tried your dynamic query without them?

    Sigerson

    "No pressure, no diamonds." - Thomas Carlyle

  • Can you post the entire statement that is causing the error?



    Microsoft Certified Master - SQL Server 2008
    Follow me on twitter: @keith_tate

    Forum Etiquette: How to post data/code on a forum to get the best help[/url]

  • This way be an object name, and optionally parameters after object name

    exec @sqlStr

    THIS way, you can execute a string command: note the parenthesis!

    exec(@sqlStr )

    Lowell


    --help us help you! If you post a question, make sure you include a CREATE TABLE... statement and INSERT INTO... statement into that table to give the volunteers here representative data. with your description of the problem, we can provide a tested, verifiable solution to your question! asking the question the right way gets you a tested answer the fastest way possible!

  • Lowell,

    Good catch! Something bothered me about that EXEC statement but I didn't stop to think about it. An idle question for anybody: are those brackets a problem or not?

    Sigerson

    "No pressure, no diamonds." - Thomas Carlyle

  • Sigerson (12/6/2013)


    Lowell,are those brackets a problem or not?

    Nope, no problem.

    If you script anything or use the shortcut menu to execute a procedure in SSMS it puts brackets around everything.

    Far away is close at hand in the images of elsewhere.
    Anon.

  • the (@sqlStr) seems to have worked, thanks

Viewing 7 posts - 1 through 6 (of 6 total)

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