VB.NET School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

Welcome to Dream.In.Code
Become a VB.NET Expert!

Join 307,219 VB.NET Programmers for FREE! Get instant access to thousands of VB.NET experts, tutorials, code snippets, and more! There are 1,625 people online right now. Registration is fast and FREE... Join Now!




Newbie question on using value of SQL function.

 

Newbie question on using value of SQL function.

pmkdatabase

20 Jul, 2009 - 06:41 PM
Post #1

New D.I.C Head
*

Joined: 14 Jun, 2009
Posts: 13

I create a scalar SQL function that returns a string, '@Name'. It works when I run it from Server Explorer, but I can't figure out how to feed the result to a textbox. I've tried several approaches including:
CODE

  Dim cnn As New SqlConnection()
  Dim cmd As SqlCommand
  Dim sName As String
  Dim rdr As SqlDataReader
  cnn.ConnectionString = CONNECTION_STRING
  cmd = New SqlCommand
  cmd.Connection = cnn
  cmd.CommandType = Data.CommandType.StoredProcedure
  cmd.CommandText = "fngetname"
  'also tried prm name = 'IDS', not '@IDS'
  cmd.Parameters.Add("@IDS", SqlDbType.Int)
  cmd.Parameters("@IDS").Value = 5
cmd.Connection.Open()
rdr = cmd.ExecuteReader()
' function is scalar but tried this way also. In any case, the reader is empty
  While rdr.Read
      sName = rdr.ToString
       frmBook.txtName.Text = sName
  End While


Thank you!

User is offlineProfile CardPM
+Quote Post


janne_panne

RE: Newbie Question On Using Value Of SQL Function.

20 Jul, 2009 - 08:41 PM
Post #2

D.I.C Addict
****

Joined: 9 Jun, 2009
Posts: 531



Thanked: 107 times
My Contributions
Reader can have many rows and columns inside of it. By rdr.Read method you go to the next row so next you have to specify the column you want to read. Try something like this:

CODE

' by column name '
sName = rdr("ColumnNameInDatabase").Value.ToString()
' or by index '
sName = rdr(0).Value.ToString()


If the reader cell's don't have Value property, try without it by using just rdr(0).ToString
User is offlineProfile CardPM
+Quote Post

pmkdatabase

RE: Newbie Question On Using Value Of SQL Function.

21 Jul, 2009 - 08:49 AM
Post #3

New D.I.C Head
*

Joined: 14 Jun, 2009
Posts: 13

The reader is empty (no data).


User is offlineProfile CardPM
+Quote Post

bflosabre91

RE: Newbie Question On Using Value Of SQL Function.

21 Jul, 2009 - 09:10 AM
Post #4

go sabres
****

Joined: 22 Feb, 2008
Posts: 676



Thanked: 13 times
My Contributions
use execute scalar to get one value from a stored procedure

CODE

        sqlProcedure = "dbo.StoProName"
        Dim cmd As New SqlCommand(sqlProcedure, con)
        cmd.CommandType = CommandType.StoredProcedure
        cmd.Parameters.Add("@sUserID", SqlDbType.VarChar)
        cmd.Parameters("@sUserID").Value = txtUserName.Text

        Try
            con.Open()
            status = Convert.ToBoolean(cmd.ExecuteScalar())
        Catch ex As Exception
            Dim err As New errormsgbox
            err.errmsg = "Error reaching database. Please contact support or try again later."
            err.updateerror()
            err.ShowDialog()
            err.Dispose()
        End Try
        con.Close()


theres an example of mine, but u will have to change it up for your use accordingly
User is offlineProfile CardPM
+Quote Post

pmkdatabase

RE: Newbie Question On Using Value Of SQL Function.

21 Jul, 2009 - 07:44 PM
Post #5

New D.I.C Head
*

Joined: 14 Jun, 2009
Posts: 13

nothing but an empty string is being returned, but I get the name if I open the function directly in Server explorer.
This is the function
CODE

ALTER FUNCTION [dbo].[fnGetName]
(
    -- Add the parameters for the function here
    @IDS int
)
RETURNS nvarchar(75)
WITH EXECUTE AS CALLER -- tried with this commented out also
AS
BEGIN

DECLARE @FullName nvarchar(75), @Lname nvarchar(50),@Fname nvarchar(50), @PatientIDS int;

    SELECT @PatientIDS=PatientIDS, @Fname=Fname, @Lname = Lname FROM tblPatient WHERE PatientIDS = @IDS

    IF @FNAME IS NULL
        SET @FullName = @Lname
    ELSE
    SET @FullName = @Lname + ', ' + @Fname
    RETURN @FullName
END


And the vb.net code:
CODE

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim strSQL As String
        Dim status
        strSQL = "dbo.fnGetName"

        conn = New SqlConnection
        conn.ConnectionString = appConn
        Dim cmd As New SqlCommand(strSQL, conn)

        cmd.CommandType = CommandType.StoredProcedure
        cmd.Parameters.Add("@IDS", SqlDbType.Int)
        cmd.Parameters("@IDS").Value = 5 ' txtUserName.Text

        Try
            conn.Open()
            status = Convert.ToString(cmd.ExecuteScalar())
            Me.TextBox1.Text = status

        Catch exp As Exception
            MessageBox.Show(exp.Message, Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Stop)
        Finally
            conn.Close()
        End Try
    End Sub
    


Thanks!
User is offlineProfile CardPM
+Quote Post

bflosabre91

RE: Newbie Question On Using Value Of SQL Function.

22 Jul, 2009 - 05:15 AM
Post #6

go sabres
****

Joined: 22 Feb, 2008
Posts: 676



Thanked: 13 times
My Contributions
usually my rule of thumb for sql is that i use store procedures for interactions with vb, and functions are used inside sql only. Try creating a stored procedure(spGetName) and i think that might fix your problem. Because you can see in the vb, it specifically says stored procedure, not a function.
User is offlineProfile CardPM
+Quote Post

pmkdatabase

RE: Newbie Question On Using Value Of SQL Function.

22 Jul, 2009 - 09:30 PM
Post #7

New D.I.C Head
*

Joined: 14 Jun, 2009
Posts: 13

Thanks for the reply. I tried that, and oddly, have the same problem - no data is being returned from the code, although it is when running the SP manually.

Here is the SP and code
CODE


ALTER PROCEDURE procGetName
@IDS int, @ReturnName nvarchar(75) OUTPUT
AS

DECLARE @FullName nvarchar(75),@Lname nvarchar(50),@Fname nvarchar(50), @PatientIDS int;

    SELECT @PatientIDS=PatientIDS, @Fname=Fname, @Lname = Lname FROM tblPatient WHERE PatientIDS = @IDS

    IF @FNAME IS NULL
        SET @FullName = @Lname
    ELSE
    SET @FullName = @Lname + ', ' + @Fname
set @ReturnName = @Fullname
RETURN

'And the code
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim cnn As New SqlConnection()
        Dim cmd As New SqlCommand
        Dim result
        Dim CONNECTION_STRING As String = "Data Source=PMK-DC2;Initial Catalog=PB.1.0_be;Integrated Security=True"
        Try


            cnn.ConnectionString = CONNECTION_STRING
            With cmd
                .CommandType = Data.CommandType.StoredProcedure
                .CommandText = "procGetname"
                .Parameters.AddWithValue("@IDS", 5)
                .Parameters.Add("@ReturnName", SqlDbType.NVarChar, 75)
                .Parameters(0).Direction = ParameterDirection.Input
                .Parameters(1).Direction = ParameterDirection.Output

                .Connection = cnn
                .Connection.Open()
            End With
            'frmBook.txtName.Text = cmd.ExecuteScalar.ToString
           'NOTHING IS RETURNED HERE - 'RESULT' IS AN EMPTY STRING
            result = cmd.ExecuteScalar
            Debug.Print(result)
        Catch ex As Exception
            MsgBox(ex.ToString)
        Finally
            cmd.Connection.Close()
            cmd = Nothing
        End Try
    End Sub
    

QUOTE(bflosabre91 @ 22 Jul, 2009 - 05:15 AM) *

usually my rule of thumb for sql is that i use store procedures for interactions with vb, and functions are used inside sql only. Try creating a stored procedure(spGetName) and i think that might fix your problem. Because you can see in the vb, it specifically says stored procedure, not a function.


User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic

Time is now: 11/21/09 10:20PM

Live VB.NET Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

VB.NET Tutorials

Reference Sheets

VB.NET Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month