INSERT MULTIPLE COLUMN DATA

  • Dear Sir,

    How to insert the dynamic Values of the variable named @name in the below mentioned query.

    declare @name varchar(500)

    declare @Cname varchar(50)

    declare @command nvarchar(500)

    declare @SQLUpdate nvarchar(500)

    declare @number int

    declare cur2 cursor for select Name from Company

    -- Create Temporary Table

    CREATE TABLE #TempTable(

    UserID varchar(30),

    CompanyName varchar(500)

    )

    open cur2

    fetch next from cur2 into @name

    WHILE @@FETCH_STATUS = 0

    begin

    SET @SQLUpdate ='INSERT INTO #TempTable (UserID,CompanyName) VALUES((SELECT [User ID],FROM [dbo].['+@name+'$User Setup],'+@name+'))'

    exec sp_executesql @SQLUpdate

    FETCH NEXT FROM cur2 into @name

    end

    close cur2

    deallocate cur2

    SELECT * from #TempTable

    DROP TABLE #TempTable

  • You have an error in the dynamic SQL part. The statement inside the VALUES part doesn't work with the comma before the FROM and you need to move the @name part inside the SELECT. Also when using a SELECT you need to remove the VALUES statement.

    Try this line instead:

    SET @SQLUpdate ='INSERT INTO #TempTable (UserID,CompanyName) SELECT [User ID],'''+@name+''' FROM [dbo].['+@name+'$User Setup]'

    If this doesn't help you, you need to explain your situation a bit better.

    ** Don't mistake the ‘stupidity of the crowd’ for the ‘wisdom of the group’! **
  • Thanks a lot 🙂

Viewing 3 posts - 1 through 2 (of 2 total)

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