0
votes

I have to insert bulk data into database and table is also created dynamically.

First have created UserDefined DataTypes

-- This is my user  defined type
CREATE TYPE [dbo].[Custom_block] AS TABLE(
    [Name] [nvarchar](200) NULL,
    [population] [nvarchar](200) NULL
)

Then i have DataTable (C#) which i have to insert into SQL table.

--My StoredProcedure :
  CREATE PROCEDURE dumpData(
     @myTableType [Custom_block] readonly,
     @tableName NVARCHAR(200)
    )

AS 
BEGIN
 DECLARE @sql NVARCHAR(MAX);
 Declare @myTableType2 as [Custom_block];
 set @myTableType2=@myTableType;

 SET @sql=N' truncate table '+QUOTENAME(@tableName)+ '
    insert into '+QUOTENAME(@tableName)+' select * from '+@myTableType2

    EXECUTE sp_executesql  @sql
END 

Error am getting:

Msg 137, Level 16, State 1, Procedure dumpData, Line 12 Must declare the scalar variable "@myTableType2"

3
remove set @myTableType2=@myTableType; use insert into select query to copy..i'm not sure.A_Sk
already tried without set @myTableType2=@myTableType; not workingSatinder singh
this wont work because you are building a command that ends with "select * from " and than you dont concatinate with a tablename but with a table itself.GuidoG
@GuidoG: insert into tableA select * from tableB this query works, but now am making this dynamically as i have to pass table name and datatable as parameterSatinder singh
yes but is @myTableType2 a varchar with value "tableB" ?GuidoG

3 Answers

1
votes

You don't require @myTableType2 you can directly insert values through table valued parameter. Try like this,

    CREATE PROCEDURE dumpData (
    @myTableType [Custom_block] readonly
    ,@tableName NVARCHAR(200)
    )
AS
BEGIN
    DECLARE @sql NVARCHAR(MAX);

    SELECT *
    INTO #temp
    FROM @myTableType

    --DECLARE @myTableType2 [Custom_block];
    --SET @myTableType2 = @myTableType;
    SET @sql = N' truncate table ' + QUOTENAME(@tableName) + '
    insert into ' + QUOTENAME(@tableName) + ' select * from #temp'

    EXECUTE sp_executesql @sql

    DROP TABLE #temp
END
0
votes

try to add the tablename as a string..

like

 CREATE PROCEDURE dumpData(
 @myTableType varchar(50),
 @tableName NVARCHAR(200)
)
 .....
 SET @sql=N' truncate table '+QUOTENAME(@tableName)+ '
insert into '+QUOTENAME(@tableName)+' select * from '+@myTableType2

I guess this would solve your issue

0
votes

I came with same scenario and solved by creating a table dynamically first and then read the data from temp table

DECLARE @insertQuery nvarchar(max)
SET @insertQuery= N'DECLARE @tempTable AS dbo.UserDefinedType
INSERT INTO @tempTable
SELECT ''39140752'',''18e22a74-bee3-462b-aee3-172df46291f3'',''test'' 
SELECT * FROM @tempTable'
EXEC (@insertQuery)