• subscribe
May 22, 2002 12:00 AM

Inserting Data When the Column Name Is a Variable

SQL Server Pro
InstantDoc ID #24989

I want to use the T-SQL INSERT statement to insert data into a table. However, the column name is a variable, and the INSERT command doesn't accept a variable argument for a column name. How can I accomplish the insert?

You can insert the data by using the sp_executesql stored procedure or the T-SQL EXEC statement, which Listing 1 shows. This sample code demonstrates how SQL Server uses the T-SQL EXEC statement to build and execute a dynamic string.



ARTICLE TOOLS

Comments
  • Anonymous User
    7 years ago
    Jul 13, 2005

    u can use any thing as a varible even the table name can, thats how the dyanamic tables are manipulated

    declare @table_name varchar(10), @col_name1 varchar(10), col_name2 varchar(10), @value_01 int, @value_02 varchar(50)

    set ...

    -- Gymnastic SQL --------
    exec ('INSERT INTO '+@table_name +'(['+@col_name1+'],['+@col_name2+']) values (''+@value_01+'',''+@value_02+'')')

    //-- Gymnastic SQL end ----

    hemal
    hemaldaha@gmail.com

  • mudassar
    8 years ago
    Jun 21, 2004

    this is very good but unfortunately it not solved my problem
    i want to use the variable as column name in the loop here is my problem when i used the intialized the vriable in the select statemnt ,it received correctly column name in the varibale but in update statement it not gives the actaul value but again the name of column,i want an immediate response from you thanks ver much here is my procedure


    ////////////////////////////////////////////////////////
    CREATE PROCEDURE dbo.call_zone
    as declare @v_code1 varchar(10),@v_code2 varchar(10),@v_counter numeric,@v_test1 varchar(15),@v_test2 varchar(15);


    DECLARE emp3 CURSOR

    FOR SELECT code1,code2,counter
    FROM feb04_dtli_guj;


    BEGIN
    OPEN emp3;
    FETCH next from emp3 INTO @v_code1,@v_code2,@v_counter;
    while @@fetch_status = 0

    Begin
    -- print @v_code1;

    -- print @v_counter;

    set @v_test1 = (select title from lhr_codes_original where city_code = @v_code2)

    update feb04_dtli_guj
    set call_zone=(select @v_test1 from lhr_codes_test where city_code = @v_code1)

    where counter=@v_counter and call_zone is null;

    FETCH next from emp3 INTO @v_code1,@v_code2,@v_counter;
    ENd

    CLOSE emp3
    DEALLOCATE emp3
    end
    GO
    ////////////////////////////////////////////////////////

You must log on before posting a comment.

Are you a new visitor? Register Here