如何从VB.net(或C#)调用sqlserver函数?是否有一些像存储过程的语法?

时间:2022-09-01 16:58:09
Public Sub cleanTables(ByVal prOKDel As Short)
     Dim sqlParams(1) As SqlParameter
     Dim sqlProcName As String
     sqlProcName = "db.dbo.sp_mySP"
     sqlParams(1) = New SqlParameter("@OKDel", prOKDel)
     Try
         dbConn.SetCommandTimeOut(0)
         dbConn.ExecuteNonQuery(CommandType.StoredProcedure, sqlProcName, sqlParams)
     Catch ex As Exception

     Finally

     End Try
End Sub

Is there

在那儿

 CommandType.StoredProcedure...CommandType.Function
sqlParams(1) = New SqlParameter("@OKDel", prOKDel)...

and finally datatable dt = dbConn.Execute(CommandType.StoredProcedure, sqlProcName, sqlParams)

最后是datatable dt = dbConn.Execute(CommandType.StoredProcedure,sqlProcName,sqlParams)

Thanks

谢谢

5 个解决方案

#1


10  

Sorry, there is no way to run a function directly. Either call it using a sql Text command

抱歉,没有办法直接运行功能。使用sql Text命令调用它

Public Sub RunFunction(ByVal input As Short)
            Using myConnection As New Data.SqlClient.SqlConnection
                Using myCommand As New Data.SqlClient.SqlCommand("Select dbo.MyFunction(@MyParam)", myConnection)
                    myCommand.CommandType = CommandType.Text
                    myCommand.Parameters.Add(New Data.SqlClient.SqlParameter("@MyParam", input))
                    myCommand.CommandTimeout = 0
                    Try
                        myCommand.ExecuteNonQuery()
                    Catch ex As Exception

                    End Try
                End Using

            End Using
        End Sub

Or Wrap a procedure round it...

或绕过它的程序......

Create Procedure RunMyFunction(@MyParam as int)
Select * FROM dbo.MyFunction(@MyParam)
Go

#2


5  

Yes you can call a function directly as demonstrated below.

是的,您可以直接调用函数,如下所示。

Dim dtaName As New SqlClient.SqlDataAdapter

dtaName.SelectCommand = New SqlClient.SqlCommand
With dtaName.SelectCommand
    .CommandTimeout = 60
    .Connection = prvcmpINC.cntINC
    .CommandType = CommandType.StoredProcedure
    .CommandText = "dbo.app_GetName"
    .Parameters.AddWithValue("@ParamToPassIn", parstrParamToPassIn)
    .Parameters.Add("@intResult", SqlDbType.Int)
    .Parameters("@intResult").Direction = ParameterDirection.ReturnValue
End With

dtaName.SelectCommand.ExecuteScalar()
intRuleNo = dtaName.SelectCommand.Parameters("@intResult").Value

#3


3  

This works for me and is based on one of the above answers using a SqlDataAdapter (note that you do not need to use one) and ExecuteScalar (can use ExecuteNonQuery as shown here):

这对我有用,并且基于上述答案之一使用SqlDataAdapter(请注意,您不需要使用一个)和ExecuteScalar(可以使用如下所示的ExecuteNonQuery):

bool res = false;
using (SqlConnection conn = new SqlConnection(GetConnectionString()))
{
    using (SqlCommand comm = new SqlCommand("dbo.MyFunction", conn))
    {
        comm.CommandType = CommandType.StoredProcedure;

        SqlParameter p1 = new SqlParameter("@MyParam", SqlDbType.Int);
        // You can call the return value parameter anything, .e.g. "@Result".
        SqlParameter p2 = new SqlParameter("@Result", SqlDbType.Bit);

        p1.Direction = ParameterDirection.Input;
        p2.Direction = ParameterDirection.ReturnValue;

        p1.Value = myParamVal;

        comm.Parameters.Add(p1);
        comm.Parameters.Add(p2);

        conn.Open();
        comm.ExecuteNonQuery();

        if (p2.Value != DBNull.Value)
            res = (bool)p2.Value;
    }
}
return res;

#4


0  

You'd just call it like you'd call a regular line of sql code

你只需要调用它就像调用常规的SQL代码行一样

#5


-2  

One of the things about functions is they can return different data types. I use:

关于函数的一个问题是它们可以返回不同的数据类型。我用:

Friend Function execFunctionReturnsString(ByVal funcName As String, Optional ByVal params As Collection = Nothing) As String
              Dim cmd As SqlCommand
              Dim param As SqlParameter
              Dim sRet As String
              Dim sCmdText As String
              Dim iParam As Integer

    cmd = New SqlCommand
    sCmdText = "select dbo." & funcName & "("
    cmd.CommandType = CommandType.Text
    cmd.Connection = _sqlConn
    cmd.CommandTimeout = 0

    If Not params Is Nothing Then
        For iParam = 1 To params.Count
            param = params(iParam)
            sCmdText = sCmdText & param.Value
            If iParam < params.Count Then
                sCmdText = sCmdText & ","
            End If
        Next
    End If

    sCmdText = sCmdText & ")"

    cmd.CommandText = sCmdText
    'If _sqlConn.State <> ConnectionState.Open Then
    _sqlConn.Open()
    'End If
    sRet = cmd.ExecuteScalar() & ""     ' if null
    _sqlConn.Close()

    Return sRet
End Function

Friend Function execFunctionReturnsInt(ByVal funcName As String, Optional ByVal params As Collection = Nothing) As Integer
    Dim cmd As SqlCommand
    Dim param As SqlParameter
    Dim iRet As Integer
    Dim sCmdText As String
    Dim iParam As Integer

    cmd = New SqlCommand
    sCmdText = "select dbo." & funcName & "("
    cmd.CommandType = CommandType.Text
    cmd.Connection = _sqlConn
    cmd.CommandTimeout = 0

    If Not params Is Nothing Then
        For iParam = 1 To params.Count
            param = params(iParam)
            sCmdText = sCmdText & param.Value
            If iParam < params.Count Then
                sCmdText = sCmdText & ","
            End If
        Next
    End If

    sCmdText = sCmdText & ")"

    cmd.CommandText = sCmdText
    'If _sqlConn.State <> ConnectionState.Open Then
    _sqlConn.Open()
    'End If
    iRet = cmd.ExecuteScalar()
    _sqlConn.Close()

Return iRet
End Function

here's an example of a call:

这是一个电话的例子:


params = New Collection
params.Add(SQLClientAccess.instance.sqlParam("@setID", DbType.String, 0, 
       _editListSetID))
valGrid.hidePKFields = SQLClientAccess.instance.execFunctionReturnsInt
      ("udf_hiddenCount", params)

and here's my sqlParam code:

这是我的sqlParam代码:


        Friend Function sqlParam(ByVal paramName As String, ByVal dBType As System.Data.DbType, ByVal iSize As Integer, ByVal sVal As String) As SqlParameter
              Dim param As SqlParameter

    param = New SqlParameter
    param.ParameterName = paramName
    param.DbType = dBType
    param.Size = iSize
    param.Value = sVal

    Return param
    End Function

HTH

HTH

#1


10  

Sorry, there is no way to run a function directly. Either call it using a sql Text command

抱歉,没有办法直接运行功能。使用sql Text命令调用它

Public Sub RunFunction(ByVal input As Short)
            Using myConnection As New Data.SqlClient.SqlConnection
                Using myCommand As New Data.SqlClient.SqlCommand("Select dbo.MyFunction(@MyParam)", myConnection)
                    myCommand.CommandType = CommandType.Text
                    myCommand.Parameters.Add(New Data.SqlClient.SqlParameter("@MyParam", input))
                    myCommand.CommandTimeout = 0
                    Try
                        myCommand.ExecuteNonQuery()
                    Catch ex As Exception

                    End Try
                End Using

            End Using
        End Sub

Or Wrap a procedure round it...

或绕过它的程序......

Create Procedure RunMyFunction(@MyParam as int)
Select * FROM dbo.MyFunction(@MyParam)
Go

#2


5  

Yes you can call a function directly as demonstrated below.

是的,您可以直接调用函数,如下所示。

Dim dtaName As New SqlClient.SqlDataAdapter

dtaName.SelectCommand = New SqlClient.SqlCommand
With dtaName.SelectCommand
    .CommandTimeout = 60
    .Connection = prvcmpINC.cntINC
    .CommandType = CommandType.StoredProcedure
    .CommandText = "dbo.app_GetName"
    .Parameters.AddWithValue("@ParamToPassIn", parstrParamToPassIn)
    .Parameters.Add("@intResult", SqlDbType.Int)
    .Parameters("@intResult").Direction = ParameterDirection.ReturnValue
End With

dtaName.SelectCommand.ExecuteScalar()
intRuleNo = dtaName.SelectCommand.Parameters("@intResult").Value

#3


3  

This works for me and is based on one of the above answers using a SqlDataAdapter (note that you do not need to use one) and ExecuteScalar (can use ExecuteNonQuery as shown here):

这对我有用,并且基于上述答案之一使用SqlDataAdapter(请注意,您不需要使用一个)和ExecuteScalar(可以使用如下所示的ExecuteNonQuery):

bool res = false;
using (SqlConnection conn = new SqlConnection(GetConnectionString()))
{
    using (SqlCommand comm = new SqlCommand("dbo.MyFunction", conn))
    {
        comm.CommandType = CommandType.StoredProcedure;

        SqlParameter p1 = new SqlParameter("@MyParam", SqlDbType.Int);
        // You can call the return value parameter anything, .e.g. "@Result".
        SqlParameter p2 = new SqlParameter("@Result", SqlDbType.Bit);

        p1.Direction = ParameterDirection.Input;
        p2.Direction = ParameterDirection.ReturnValue;

        p1.Value = myParamVal;

        comm.Parameters.Add(p1);
        comm.Parameters.Add(p2);

        conn.Open();
        comm.ExecuteNonQuery();

        if (p2.Value != DBNull.Value)
            res = (bool)p2.Value;
    }
}
return res;

#4


0  

You'd just call it like you'd call a regular line of sql code

你只需要调用它就像调用常规的SQL代码行一样

#5


-2  

One of the things about functions is they can return different data types. I use:

关于函数的一个问题是它们可以返回不同的数据类型。我用:

Friend Function execFunctionReturnsString(ByVal funcName As String, Optional ByVal params As Collection = Nothing) As String
              Dim cmd As SqlCommand
              Dim param As SqlParameter
              Dim sRet As String
              Dim sCmdText As String
              Dim iParam As Integer

    cmd = New SqlCommand
    sCmdText = "select dbo." & funcName & "("
    cmd.CommandType = CommandType.Text
    cmd.Connection = _sqlConn
    cmd.CommandTimeout = 0

    If Not params Is Nothing Then
        For iParam = 1 To params.Count
            param = params(iParam)
            sCmdText = sCmdText & param.Value
            If iParam < params.Count Then
                sCmdText = sCmdText & ","
            End If
        Next
    End If

    sCmdText = sCmdText & ")"

    cmd.CommandText = sCmdText
    'If _sqlConn.State <> ConnectionState.Open Then
    _sqlConn.Open()
    'End If
    sRet = cmd.ExecuteScalar() & ""     ' if null
    _sqlConn.Close()

    Return sRet
End Function

Friend Function execFunctionReturnsInt(ByVal funcName As String, Optional ByVal params As Collection = Nothing) As Integer
    Dim cmd As SqlCommand
    Dim param As SqlParameter
    Dim iRet As Integer
    Dim sCmdText As String
    Dim iParam As Integer

    cmd = New SqlCommand
    sCmdText = "select dbo." & funcName & "("
    cmd.CommandType = CommandType.Text
    cmd.Connection = _sqlConn
    cmd.CommandTimeout = 0

    If Not params Is Nothing Then
        For iParam = 1 To params.Count
            param = params(iParam)
            sCmdText = sCmdText & param.Value
            If iParam < params.Count Then
                sCmdText = sCmdText & ","
            End If
        Next
    End If

    sCmdText = sCmdText & ")"

    cmd.CommandText = sCmdText
    'If _sqlConn.State <> ConnectionState.Open Then
    _sqlConn.Open()
    'End If
    iRet = cmd.ExecuteScalar()
    _sqlConn.Close()

Return iRet
End Function

here's an example of a call:

这是一个电话的例子:


params = New Collection
params.Add(SQLClientAccess.instance.sqlParam("@setID", DbType.String, 0, 
       _editListSetID))
valGrid.hidePKFields = SQLClientAccess.instance.execFunctionReturnsInt
      ("udf_hiddenCount", params)

and here's my sqlParam code:

这是我的sqlParam代码:


        Friend Function sqlParam(ByVal paramName As String, ByVal dBType As System.Data.DbType, ByVal iSize As Integer, ByVal sVal As String) As SqlParameter
              Dim param As SqlParameter

    param = New SqlParameter
    param.ParameterName = paramName
    param.DbType = dBType
    param.Size = iSize
    param.Value = sVal

    Return param
    End Function

HTH

HTH