Results 1 to 2 of 2
  1. #1
    Join Date
    Jul 2003

    Unanswered: Creating Dynamic Variables

    Is there any way I can create variables dynamically in SQL server procedures?

    e.g., I initially declare variable

    and in a for loop with variable @i,

    I have @str='@col'+@i
    if @i=1 then the @str='@col1'
    and try to insert the value this variable holds into a table as

    insert into table1 values(@str)

    Here I want to insert the value of @col1(which is 1) and NOT '@col1'

    I tried so many time unsuccessfully.Has anyone done this kind of stuff before?any work arounds for this?

    appreciate u'r help..


  2. #2
    Join Date
    Jun 2003
    Provided Answers: 1
    Chances are you can accomplish your objectives using standard SQL, with maybe a little help from temporary tables, table variables, or case statements. I don't understand what you are trying to do, but your code looks like SQL written by a VB programmer (loops, inserting parameters, etc...). These are legitimate tools for SQL, but most procedures don't require them.

    Using a dynamic SQL statement may be an option, either to assign the value to @str or for the insert statement, but dynamic SQL is tricky because it executes in a distinct environment and your variables go out of scope.

    If you could briefly describe your application, relevant table structures, and the task you are trying to perform, I may be able to give your some programming algorythms that are more appropriate for SQL.


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts