【问题标题】:How to call a function in a command?如何在命令中调用函数?
【发布时间】:2014-12-11 17:06:59
【问题描述】:

我想使用“MyPlaces”功能。我应该用什么代替commandType.StoredProcedure

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string connStr = ConfigurationManager.ConnectionStrings["MyDbConn"].ToString();
        SqlConnection conn = new SqlConnection(connStr); 
        SqlCommand cmd = new SqlCommand("MyPlaces", conn);
        cmd.CommandType = CommandType.StoredProcedure; //This part gives me an error 
        string email = Session["oldemailuser"].ToString();
        cmd.Parameters.Add(new SqlParameter("@email", email));

        conn.Open();
        SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);

        string s = "<br />";
        while (rdr.Read())
        {
          string name = s + " " + rdr.GetString(rdr.GetOrdinal("name"))
                        + "   located in ";
          string location = rdr.GetString(rdr.GetOrdinal("location")) 
                            + "&nbsp;&nbsp";


         Label lbl_name = new Label();
         lbl_name.Text = email;
         form1.Controls.Add(lbl_name);

         Label lbl_location = new Label();
         lbl_location.Text = email;
         form1.Controls.Add(lbl_location);

     }
 }

【问题讨论】:

  • 什么问题,哪里出错了?
  • 一些解释会好吗?例如基于 SqlClient,我们是否假设您的意思是 SqlServer UDF? UDF 是标量函数还是表函数?
  • 这是我的函数 ALTER function MyPlaces (@email varchar(50)) 返回表 AS RETURN select p.name ,p.location from likes l inner join place p on l.place_id = p.id其中 l.user_email = @email

标签: c# function


【解决方案1】:

希望你的 sql 函数名是“Myplaces”。如果是这样,那么用这个修改你的代码:

string email = Session["oldemailuser"].ToString();

SqlConnection conn = new SqlConnection(connStr); 
SqlCommand cmd = new SqlCommand(conn);
cmd.CommandText = "SELECT MyPlaces(@email)";
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add(new SqlParameter("@email", email));
conn.Open();    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-02
    • 1970-01-01
    • 2019-09-09
    • 2020-01-15
    • 2021-05-12
    • 2022-01-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多