6
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)

Thanks

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794

5 Answers5

12

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

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
ziad mansour
  • 349
  • 6
  • 25
digiguru
  • 12,724
  • 20
  • 61
  • 87
  • 2
    Two comments on this: 1 - it assumes a table-valued function and 2 - What is the purpose of sqlParams(1) ? It doesn't seem to be used anywhere. Otherwise very helpful, thanks – JosephStyons Jul 12 '11 at 19:38
  • I will use `Select dbo.MyFunction(@MyParam)` – Jaider Jul 25 '14 at 15:04
7

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
sth
  • 222,467
  • 53
  • 283
  • 367
Kevin M Cain
  • 1
  • 1
  • 2
  • I don't think `ExecuteScalar()` is necessary. I haven't had any problems using this method with `ExecuteNonQuery()`. – Billy Jo Nov 29 '10 at 18:56
4

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):

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;
Gonzalo.-
  • 12,512
  • 5
  • 50
  • 82
rasika
  • 131
  • 1
  • 6
0

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

Fredou
  • 19,848
  • 10
  • 58
  • 113
-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:


        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

Beth
  • 9,531
  • 1
  • 24
  • 43