1

我需要能够在 c#.net 中将字符串转换为 hierarchyid - 我不能使用存储过程。

当我传入路径(字符串)时,查询失败,因为路径是这样存储的 '/' 而不是 /

我可以将其转换为另一种类型吗?

SqlCommand command = new SqlCommand("INSERT Structure (Path,Description,ParentID) " +
    "VALUES(" + path + ".GetDescendant(" + lastChildPath +
    ", NULL) " +
    ",@description, @parentId", _connection);

——BitKFu

我已经添加了,这是它产生的 sql 查询:

CommandText = "INSERT Structure (Path,Description,ParentID) VALUES(CAST(/ AS hierarchyid).GetDescendant(NULL, NULL) ,@description, @parentId"

我收到以下错误:ex = {“'/' 附近的语法不正确。”}

--ck

这就是我所期待的

"INSERT Structure (Path,Description,ParentID) VALUES(/.GetDescendant(NULL, NULL) ,'Test', 1"

——保罗·鲁安

我已经看过这个页面,但它并没有真正帮助,除非我忽略了什么?

谢谢

克莱尔

4

2 回答 2

3

如果只有 '' 是错误的,我会尝试投射它。

SqlCommand command = new SqlCommand("INSERT Structure (Path,Description,ParentID) " +
    "VALUES(CAST('"+path+"' AS hierarchyid).GetDescendant(" + lastChildPath +
    ", NULL) " +
    ",@description, @parentId", _connection);
于 2010-08-17T08:42:59.647 回答
1

我意识到这很旧,并且有答案,但是我想添加另一个选项,因为我遇到了这个问题,试图做同样的事情。

您可以使用 Microsoft.SqlServer.Types 命名空间和类似的东西在 C# 中将字符串转换为 HierarchyId:

SqlHierarchyId hierarchyIdRepresentation = (SqlHierarchyId)Convert.ChangeType(input, typeof(SqlHierarchyId))

或者

SqlHierarchyId hierarchyIdRepresentation = SqlHierarchyId.Parse(input)

.Parse()只要有从字符串的转换并且.ToString()该类型的方法SqlHierarchyId覆盖标准字符串运算符以返回规范表示,就会自动调用该方法。

来源:https ://msdn.microsoft.com/en-us/library/microsoft.sqlserver.types.sqlhierarchyid_methods(v=sql.105).aspx

于 2015-12-31T19:29:50.347 回答