如何在C#中调用SQL函数?

我在SQL中创建了一个函数,现在我需要在我的C#应用​​程序中使用该函数。

我尝试使用这样的东西,但似乎我做错了,因为我得到了:

Must declare the scalar value '@2064734117' 

…当我将2064734117作为第一个参数并将1作为第二个参数时。 这是我正在谈论的代码:

 SqlConnection con = new SqlConnection(clsDb.connectionString); string query = string.Format("select Function1(@{0},@{1}) ", int.Parse(e.CurrentRow.Cells["CodeMeli"].Value.ToString()),1); con.Open(); SqlCommand cmd = new SqlCommand(query,con); SqlDataAdapter READER = new SqlDataAdapter(); READER.SelectCommand = cmd; DataTable table = new DataTable(); READER.Fill(table); radGridView1.DataSource = table; con.Close(); 

我的函数接受两个整数参数并返回一个表。 我在Visual Studio中检查了它并且它有效,但我无法在我的应用程序中使用它。

这是我的function声明:

 ALTER FUNCTION dbo.Function1 ( /* @parameter1 int = 5, @parameter2 datatype */ @ID int, @clsTypeID int ) RETURNS TABLE/* @table_variable TABLE (column1 datatype, column2 datatype) */ AS /*BEGIN */ /* INSERT INTO @table_variable SELECT ... FROM ... */ RETURN SELECT * FROM tblCLASS2 WHERE STNID = @ID AND CLASSTYPEID = @clsTypeID /*END */ /*GO*/ 

你的SQL有点偏,它应该是:

  string query = string.Format("select * from dbo.Function1({0},{1});", int.Parse(e.CurrentRow.Cells["CodeMeli"].Value.ToString()),1); 

您可能希望使用SqlParameter对象来阻止sql注入:

  string query = "select * from dbo.Function1(@pa1,@par2);"; cmd.Parameters.Add("@par1", SqlDbType.Int).Value = int.Parse(e.CurrentRow.Cells["CodeMeli"].Value.ToString()); cmd.Parameters.Add("@par2", SqlDbType.Int).Value = 1; 

乍一看,我能看到的第一件事是你没有指定对象所有者/架构; 这是函数所必需的,所以应该select dbo.Function1(...

第二:看看你对string.Format的调用产生了什么; 即为另一个整数生成@1@n ,但这不是有效的参数名称。 这很方便,因为

第三:你没有添加任何参数

第四:对于表UDF(而不是标量UDF),您必须select * from dbo.Function1(... ,而不仅仅是select dbo.Function1(...

你可以这样做:

  myConn.Open(); //generating the new command for our database SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT OBJECTID_1, NDNT as theAddress, MIN(ABS(x - " + double.Parse(x.ToString()) + ") + ABS(y - " + double.Parse(y.ToString()) +")) from dbo.DWH_OUTPUT GROUP BY OBJECTID_1,NDNT HAVING (MIN(ABS(x - " + double.Parse(x.ToString()) + ") + ABS(y - " + double.Parse(y.ToString()) + ")) = (Select MIN(ABS(ax - " + double.Parse(x.ToString()) + ") + ABS(ay - " + double.Parse(y.ToString()) + ")) from dbo.DWH_OUTPUT a ) )"; cmd.Connection = myConn; //getting some more ado.net objects SqlDataAdapter da = new SqlDataAdapter(); DataSet ds = new DataSet(); da.SelectCommand = cmd; da.Fill(ds, @"Addresses"); if (ds.Tables[0].Rows.Count > 0) { theAddress = ds.Tables[0].Rows[0][@"theAddress"] + @" (proximity address)"; } myConn.Close(); 

请注意,在此示例中,您将SqlCommand的CommandType设置为CommandType.Text 。 指定命令参数(即代码段中的select函数),然后使用Fill方法填充数据集。 然后,您可以像通常使用标准ado.net一样从行中获取值。

如果你需要调用存储过程,请看看:

如何从ado.net调用TSQL函数

您需要具有所有者/模式名称的完全限定function名称可在以下链接中使用的工作示例: