【问题标题】:Convert a string to a hierarchyid in C#在C#中将字符串转换为hierarchyid
【发布时间】:2010-08-17 08:20:13
【问题描述】:

我需要能够在 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"

-- 保罗·鲁安

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

谢谢

克莱尔

【问题讨论】:

  • 示例输入和输出会很有用...
  • This page 可能会有所帮助。
  • 你必须引用 / ,比如 '/'

标签: c# tsql hierarchyid


【解决方案1】:

如果只有 '' 错误,我会尝试转换它。

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

【讨论】:

  • 感谢 BitKFu - 它确实需要引号
  • 再试一次,我想你错过了报价。
【解决方案2】:

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

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

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

SqlHierarchyId hierarchyIdRepresentation = SqlHierarchyId.Parse(input)

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

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

【讨论】:

    猜你喜欢
    • 2020-06-13
    • 2014-05-02
    • 2020-02-20
    • 2023-03-28
    • 1970-01-01
    • 2011-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多