C# 使用Dapper将大数组插入到已声明的SQL Server表中

C# 使用Dapper将大数组插入到已声明的SQL Server表中,c#,sql-server,tsql,dapper,C#,Sql Server,Tsql,Dapper,我有一个整数列表,我正试图将这些值插入一个临时表中,并使用Dapper语句声明。我尝试了几种组合,但最终导致“,”附近的语法错误错误 Dapper甚至可以区分局部变量和Dapper查询参数,两者都带有@前缀吗 列表输出=null; 列表输入=新列表 { 1, 2, 3 }; var sql=@“DECLARE@tentable表(Id INT) 插入@attreable VALUES(@Ids); 从@tentable;中选择*; 使用(var connection=new SqlConnec

我有一个整数列表,我正试图将这些值插入一个临时表中,并使用Dapper语句声明。我尝试了几种组合,但最终导致“,”附近的
语法错误
错误

Dapper甚至可以区分局部变量和Dapper查询参数,两者都带有
@
前缀吗

列表输出=null;
列表输入=新列表
{
1, 2, 3
};
var sql=@“DECLARE@tentable表(Id INT)
插入@attreable VALUES(@Ids);
从@tentable;中选择*;
使用(var connection=new SqlConnection(FiddleHelper.GetConnectionStringSqlServer())
{
output=connection.Query(sql,new{Ids=input}).ToList();
}

请注意,输入列表可以大于1000。

Dapper将列表转换为单独的参数,适合包含在in谓词中,但不适合插入。。。值查询。相反,将值作为JSON传递,这对于大型列表来说也比使用单独的参数便宜得多。乙二醇

List<int> output = null;

List<int> input = new List<int>
    {
        1, 2, 3
    };

var sql = @"
DECLARE @tempTable TABLE (Id INT)
INSERT INTO @tempTable(id) select value from openjson( @Ids ); 
        
SELECT * FROM @tempTable;";

var inputJson = System.Text.Json.JsonSerializer.Serialize(input);

using (var con = new SqlConnection("server=localhost;database=tempdb;integrated security=true;trust server certificate=true")) 
{
    output = con.Query<int>(sql, new { Ids = inputJson }).ToList();
}
列表输出=null;
列表输入=新列表
{
1, 2, 3
};
var sql=@”
声明@tentable(Id INT)
插入到@tentable(id)中,从openjson中选择值(@Ids);
从@tentable;中选择*;
var inputJson=System.Text.Json.JsonSerializer.Serialize(输入);
使用(var con=new SqlConnection(“server=localhost;database=tempdb;integrated security=true;trust server certificate=true”))
{
output=con.Query(sql,new{Ids=inputJson}).ToList();
}

Dapper将列表转换为单独的参数,适合包含在in谓词中,但不适合插入。。。值查询。相反,将值作为JSON传递,这对于大型列表来说也比使用单独的参数便宜得多。乙二醇

List<int> output = null;

List<int> input = new List<int>
    {
        1, 2, 3
    };

var sql = @"
DECLARE @tempTable TABLE (Id INT)
INSERT INTO @tempTable(id) select value from openjson( @Ids ); 
        
SELECT * FROM @tempTable;";

var inputJson = System.Text.Json.JsonSerializer.Serialize(input);

using (var con = new SqlConnection("server=localhost;database=tempdb;integrated security=true;trust server certificate=true")) 
{
    output = con.Query<int>(sql, new { Ids = inputJson }).ToList();
}
列表输出=null;
列表输入=新列表
{
1, 2, 3
};
var sql=@”
声明@tentable(Id INT)
插入到@tentable(id)中,从openjson中选择值(@Ids);
从@tentable;中选择*;
var inputJson=System.Text.Json.JsonSerializer.Serialize(输入);
使用(var con=new SqlConnection(“server=localhost;database=tempdb;integrated security=true;trust server certificate=true”))
{
output=con.Query(sql,new{Ids=inputJson}).ToList();
}

您正在使用一个匿名数组:new{Ids=input}。改为int[]:new int[]{1,2,3}@jdweng与只传递
input.ToArray()
,这会产生错误:
在此上下文中不允许枚举参数序列(数组、列表等)
?您使用的是匿名数组:new{Ids=input}。改为int[]:new int[]{1,2,3}@jdweng与只传递
input.ToArray()
,这会产生错误:
在此上下文中不允许枚举参数序列(数组、列表等)