【问题标题】:how to set return type of a stored procedure according to a specific table如何根据特定表设置存储过程的返回类型
【发布时间】:2013-09-19 09:49:07
【问题描述】:

我做了一个像这样的动态存储过程

CREATE PROCEDURE [dbo].[MyProcedure]
    @pSelect nvarchar(max)
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @SQL nvarchar(max)

    SET @SQL = 'select ' + @pSelect + ' from tabel1';

    EXEC (@SQL)
END

在更新我的实体数据模型时,在 context.cs 中,上述存储过程的形式为

 virtual int MyProcedure(string pSelect)
            {
                var pSelectParameter = pSelect != null ?
                    new ObjectParameter("pSelect", pSelect) :
                    new ObjectParameter("pSelect", typeof(string));

                return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("MyProcedure", pSelectParameter);
            }

关于从 c# 代码调用存储过程

var result = myDataModel.MyProcedure("Select * From table1").tolist();

上面的代码显示错误,因为 MyProcedure 正在返回一个整数返回类型
那么如何根据传递给它的 tje select 查询设置存储过程的返回类型

如何修改我的存储过程,使其返回类型是任何特定的表类型

【问题讨论】:

  • Entity Framework 支持原生查询:Entity Framework Raw SQL Queries - 这就是你想要做的吗?
  • 另外,您的代码结果为"select Select * From table1 from tabel1",但我明白了。

标签: c# sql-server stored-procedures ado.net-entity-data-model


【解决方案1】:

在这种情况下,您必须欺骗代码。

CREATE PROCEDURE [dbo].[MyProcedure]
    @pSelect nvarchar(max)
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @SQL nvarchar(max)

    SET @SQL = 'select ' + @pSelect + ' from tabel1';

    EXEC (@SQL)

   --Remove the below line once you have added the stored procedure to the dbml file.
    select * from table1
END

创建sp后,拖放到c#dbml文件中。那么您可以通过删除“select * from table1”这一行来更改 sp。

注意:如果 table1 中没有这些列,则 select 语句中的直接值(任何数据类型)如“select 1 as colmumn1, 'string' as colmumn2, cast('10/01/1900' as datetime ) 作为 table1 中的 colmumn3"

【讨论】:

    【解决方案2】:

    只需在参数中添加 @ 符号即可。

     var pSelectParameter = pSelect != null ?
                    new ObjectParameter("@pSelect", pSelect) :
                    new ObjectParameter("@pSelect", typeof(string));
    

    可能这应该有效,我相信您在此参数中仅传递列名。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-14
      • 2017-12-16
      相关资源
      最近更新 更多