【发布时间】:2019-05-01 03:04:22
【问题描述】:
我在带有 Visual Studio 2017 的 Windows 环境中使用 C# 和 SQL Server。我正在尝试将数据表(称为 @profiles)传递给 SQL 脚本。
为此,我首先必须创建一个与传递的数据表匹配的表类型。
问题是,在我尝试使用传递的数据表填充一个新表时,我遇到了两个异常之一:
“列、参数或变量@profiles。: 找不到数据类型 ProfileIdTableType。”
“表类型参数'@profiles'必须有一个有效的类型名称。”
根据我的搜索,我可以发现具有新表类型的数据表通常与过程一起使用,但无论如何 - 我仍然遇到上述异常。
我试图声明一个新的表类型并使用@profiles,但没有成功。
当我声明我用来传递的SqlParameter时,我一般会遇到第一个异常(找不到类型)
我应该提一下,我在 SQL Server 的“可编程性”部分中找不到创建的类型(但我的类型是 temp,所以应该是)
这是我用来将数据表从 C# 传递到脚本的 2 种方法:
SqlParameter @profiles = new SqlParameter("@profiles", profileIds.Tables[0]);
profiles.TypeName = "ProfileIdTableType";
或:
DbParameter @profiles = new SqlParameter("@profiles", profileIds.Tables[0]);
然后使用它:
updatedProfiles = (int)DbAdminOps.ExecuteNonQueryCommand(updateProfileSettingsCommand, CommandType.Text, new DbParameter[] { @profiles, @updatedTemplate }, null);
这是我上次使用的 SQL 脚本(但尝试了许多此处未提供的变体)
-- create a table type of profile Ids passed by user
CREATE TYPE ProfileIdTableType AS TABLE (ID INT)
go
DECLARE @PRFL ProfileIdTableType
GO
CREATE PROCEDURE PopulateTable
@profiles ProfileIdTableType READONLY
AS
INSERT INTO @PRFL(ID)
SELECT [ID] FROM @profiles
GO
@profiles ProfileIdTableType
EXEC PopulateTable @profiles
go
我希望@profiles 被识别为一个表,因此我可以在我的脚本中使用它,但我得到的只是异常。我付出了很多努力,但就是做不到。
浏览了所有堆栈溢出问题、youtube、微软文档和网络。
如果有任何我遗漏的重要信息,请告诉我。
非常感谢一些建议。
干杯!
【问题讨论】:
-
使用表参数时使用
System.Data.SqlDbType.Structured作为SqlDbType。 -
可以添加存储过程的代码
PopulateTable吗?
标签: c# sql-server