我必须插入大量数据到数据库和表也动态创建。
首先创建UserDefined DataTypes
-- This is my user defined type
CREATE TYPE [dbo].[Custom_block] AS TABLE(
[Name] [nvarchar](200) NULL,
[population] [nvarchar](200) NULL
)
然后我有数据表(c#),我必须插入到SQL表。
--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
输入错误:
Msg 137, Level 16, State 1, Procedure dumpData, Line 12必须声明@myTableType2
您不需要@myTableType2,您可以直接通过表值参数插入值。试试这样,
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
尝试将tablename添加为字符串..
和
CREATE PROCEDURE dumpData(
@myTableType varchar(50),
@tableName NVARCHAR(200)
)
.....
SET @sql=N' truncate table '+QUOTENAME(@tableName)+ '
insert into '+QUOTENAME(@tableName)+' select * from '+@myTableType2
我想这会解决你的问题
我遇到了同样的情况,首先动态创建一个表,然后从临时表
读取数据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)