无法使用TVF结果更新表格

时间:2015-10-08 20:45:51

标签: .net sql-server sql-server-2014 sqlclr

我有一个复杂的CLR函数,它返回一行。我可以使用Cross Apply来选择工作正常但Update或Insert失败的结果。选择始终有效但插入,选择和更新失败并出现以下错误,此错误不会出现在选择查询中。

Msg 6522, Level 16, State 1, Line 1
A .NET Framework error occurred during execution of user-defined routine or aggregate "AppendCLR": 
System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
System.ArgumentOutOfRangeException: 
   at System.Collections.ArrayList.get_Item(Int32 index)
   at AppendCLR.ProcessData(String EnrollmentID,String InstituteCode)
   at AppendCLR.UserDefinedFunctions(SqlString EnrollmentID,SqlString InstituteCode)
.
The statement has been terminated.

TestCLR是我需要使用CLR函数AppendCLR的结果更新的表。 #TestCLR_TEMP@TestCLR_TEMP分别是临时变量和表变量。

这不起作用:

update a set
a.ID=b.ID,
a.Branch=b.Branch,
a.CourseID=b.CourseID, 
a.EnrolDate=b.EnrolDate, 
a.CourseTag=b.CourseTag, 
a.Micro=b.Micro, 
a.StudentTag=b.StudentTag FROM TestCLR a cross apply 
dbo.AppendCLR([EnrollmentID],[InstituteCode]) b

这也不起作用:

select *  into #TestCLR_TEMP from  dbo.AppendCLR([EnrollmentID],[InstituteCode])

OR

select *  into TestCLR_TEMP from  dbo.AppendCLR([EnrollmentID],[InstituteCode])

然而这有效:

declare table @TestCLR_TEMP (ID bigint,
Branch varchar(100),
CourseID bigint,
EnrolDate DateTime,
CourseTag varchar(100),
Micro varchar(100),
StudentTag varchar(100))

insert into @TestCLR_TEMP select 
a.ID,
b.Branch,
b.CourseID, 
b.EnrolDate, 
b.CourseTag, 
b.Micro, 
b.StudentTag FROM TestCLR  a cross apply 
dbo.AppendCLR([EnrollmentID],[InstituteCode]) b
--I have now my results in @TestCLR_TEMP, I can perform an inner join to append these results back to my original table TestCLR

这始终有效:

Select * from dbo.AppendCLR(123,456)

基本上所有插入,更新都会在真实表格上尝试时失败.SSMS中的错误并没有说明重要但我可以根据需要发布。 谢谢!

1 个答案:

答案 0 :(得分:0)

我觉得自己很愚蠢,但原始错误为Transaction Context In Use By Another Session,同时将选择查询的结果读入DataTable,而我在阅读此空System.ArgumentOutOfRangeException时获得DataTable

修复程序在连接字符串中使用Enlist=false

我知道我应该专注于错误报告,但感谢你们的努力。