Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. Database & SysAdmin
  3. Database
  4. How to retrieve data from stored function?

How to retrieve data from stored function?

Scheduled Pinned Locked Moved Database
questiondatabasecsharpvisual-studiotesting
7 Posts 2 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • C Offline
    C Offline
    Chodici Mrkev
    wrote on last edited by
    #1

    Hi, I tried to create my first stored function in SQL: I wrote this: CREATE FUNCTION dbo.Function1 ( @Username varchar(50) ) RETURNS TABLE AS RETURN ( SELECT * FROM Users WHERE Username = @Username) and I wanted to retrieve all data from record in the database about this user. I am absolute newbie in this, and I have this code to save data to the database: Dim cmd As New SqlClient.SqlCommand("RegisterUser", vilemConn) cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.Add("@Username", txtUsername.Text) cmd.Parameters.Add("@Password", inputPassword1.Value) My question is: How can I get data from the database? (I want to save them to the structure.) And the second question: When I tried this with Run inline function in VS.NET and when I set the value of @Username="blablabla" it got the result, but when I set this value to NULL it said No rows affected. No more results. (0 row(s) returned), despite I have there (for testing purposes only, there will never be any NULL Username:)) few NULL values?

    C 1 Reply Last reply
    0
    • C Chodici Mrkev

      Hi, I tried to create my first stored function in SQL: I wrote this: CREATE FUNCTION dbo.Function1 ( @Username varchar(50) ) RETURNS TABLE AS RETURN ( SELECT * FROM Users WHERE Username = @Username) and I wanted to retrieve all data from record in the database about this user. I am absolute newbie in this, and I have this code to save data to the database: Dim cmd As New SqlClient.SqlCommand("RegisterUser", vilemConn) cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.Add("@Username", txtUsername.Text) cmd.Parameters.Add("@Password", inputPassword1.Value) My question is: How can I get data from the database? (I want to save them to the structure.) And the second question: When I tried this with Run inline function in VS.NET and when I set the value of @Username="blablabla" it got the result, but when I set this value to NULL it said No rows affected. No more results. (0 row(s) returned), despite I have there (for testing purposes only, there will never be any NULL Username:)) few NULL values?

      C Offline
      C Offline
      Colin Angus Mackay
      wrote on last edited by
      #2

      Be careful of the differences between a "User Defined Function" (what you have here) and a "Stored Procedure". (There is no such thing as a "Stored Function") User Defined Functions (UDF) are more restrictive and can only use deterministic statements and functions. They cannot change the state of the database either. However they can still be useful as they can be inserted into complex SELECT statements to reduce the complexity and make them easier to read. But there is a performance penalty for this as the query optimiser cannot optimise what is in the UDF with the rest of the SELECT statement. If you want to use a UDF from .NET code you need to wrap it up in a SELECT like this:

      SELECT * FROM dbo.Function1(@UserName)

      As to your questions. The .NET code you've provided does not match with the SQL code above it, so I don't really know how to answer. chodicimrkev wrote: How can I get data from the database? (I want to save them to the structure.) Also, I am not sure what you mean by "the structure". What structure? Do you want to read the data into a dataset, or your own objects or what?


      "If a man empties his purse into his head, no man can take it away from him, for an investment in knowledge pays the best interest." -- Joseph E. O'Donnell Not getting the response you want from a question asked in an online forum: How to Ask Questions the Smart Way!

      C 1 Reply Last reply
      0
      • C Colin Angus Mackay

        Be careful of the differences between a "User Defined Function" (what you have here) and a "Stored Procedure". (There is no such thing as a "Stored Function") User Defined Functions (UDF) are more restrictive and can only use deterministic statements and functions. They cannot change the state of the database either. However they can still be useful as they can be inserted into complex SELECT statements to reduce the complexity and make them easier to read. But there is a performance penalty for this as the query optimiser cannot optimise what is in the UDF with the rest of the SELECT statement. If you want to use a UDF from .NET code you need to wrap it up in a SELECT like this:

        SELECT * FROM dbo.Function1(@UserName)

        As to your questions. The .NET code you've provided does not match with the SQL code above it, so I don't really know how to answer. chodicimrkev wrote: How can I get data from the database? (I want to save them to the structure.) Also, I am not sure what you mean by "the structure". What structure? Do you want to read the data into a dataset, or your own objects or what?


        "If a man empties his purse into his head, no man can take it away from him, for an investment in knowledge pays the best interest." -- Joseph E. O'Donnell Not getting the response you want from a question asked in an online forum: How to Ask Questions the Smart Way!

        C Offline
        C Offline
        Chodici Mrkev
        wrote on last edited by
        #3

        Thank you for your answer, you saved me for the second time :) When you help me with stored procedure last time, I decided to make more user-friendly interface - I decided to add possibility of editing of existing records - My idea was to make a function ReadUserData, which will be called in two cases: 1)During the editing 2)After successful registration to show all data again. So I created data structure that will be used to save of the data of edited user. Private Structure UserData Dim strRecordID As Integer Dim strAllowed As Integer Dim strName As String Dim strSurname As String Dim strClass As String Dim strEmail As String Dim strUsername As String Dim strPassword As String Dim strSkin As String Dim strImagePath As String End Structure What I want is to get the data from db to this structure, then I need to update it. I haven't a clue how to do it so I decided to try to make a function: ALTER FUNCTION dbo.Function1 ( @Username varchar(50) ) RETURNS TABLE AS RETURN ( SELECT * FROM Users WHERE Username = @Username) Although I don't know how to retrieve data from db, so I was thinking about something like: Dim cmd As New SqlClient.SqlCommand("RegisterUser", vilemConn) cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.Add("@Username", txtUsername.Text) cmd.Parameters.Add("@Password", inputPassword1.Value)but in the other way - to get the values of these parameters. Thanks a lot

        C 2 Replies Last reply
        0
        • C Chodici Mrkev

          Thank you for your answer, you saved me for the second time :) When you help me with stored procedure last time, I decided to make more user-friendly interface - I decided to add possibility of editing of existing records - My idea was to make a function ReadUserData, which will be called in two cases: 1)During the editing 2)After successful registration to show all data again. So I created data structure that will be used to save of the data of edited user. Private Structure UserData Dim strRecordID As Integer Dim strAllowed As Integer Dim strName As String Dim strSurname As String Dim strClass As String Dim strEmail As String Dim strUsername As String Dim strPassword As String Dim strSkin As String Dim strImagePath As String End Structure What I want is to get the data from db to this structure, then I need to update it. I haven't a clue how to do it so I decided to try to make a function: ALTER FUNCTION dbo.Function1 ( @Username varchar(50) ) RETURNS TABLE AS RETURN ( SELECT * FROM Users WHERE Username = @Username) Although I don't know how to retrieve data from db, so I was thinking about something like: Dim cmd As New SqlClient.SqlCommand("RegisterUser", vilemConn) cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.Add("@Username", txtUsername.Text) cmd.Parameters.Add("@Password", inputPassword1.Value)but in the other way - to get the values of these parameters. Thanks a lot

          C Offline
          C Offline
          Colin Angus Mackay
          wrote on last edited by
          #4

          First, an optimisation tip. Although I'm thinking it may not be important in VB.NET as the ByVal and ByRef must be declared in method parameters - In C# classes are by reference by default and structures are by value by default. However, I still think the general rule is sound that a structure should always be small (no more than 16 bytes is one figure I've heard). So, for something like this a class would be better (in my opinion). Looking at the structure you've given. I'm assuming that RecordId is the primary key of the table. If that is the case then UserName should have a unique constraint applied to it also to make sure that two users with the same UserName do not get inserted in the database. Disclaimer: I've tried to write in VB.NET, which isn't my language - I've not done any VB since version 3, so please be aware that there may be errors in the syntax. To get the data from the database create a stored procedure that is similar to this:

          CREATE PROCEDURE GetUserDetails(@UserName varchar(64), @Password varchar(64))
          AS
          -- This should always return zero or one records only.
          SELECT RecordId, Allowed, Name, Surname, Class, Email, UserName, Password, Skin, ImagePath
          FROM Users
          WHERE Username = @UserName
          AND Password = @Password
          GO

          Then in your .NET application some code like this:

          Dim cmd As New SqlClient.SqlCommand("GetUserDetails", vilemConn)
          cmd.CommandType = CommandType.StoredProcedure
          cmd.Parameters.Add("@Username", txtUsername.Text)
          cmd.Parameters.Add("@Password", inputPassword1.Value)

          ' The data from the Select can be returned in to a DataSet or through a DataReader
          ' As you are populating your own structure it is probably better to use the DataReader
          Dim dataReader As cmd.ExecuteDataReader()
          Dim details As New UserData()
          If dataReader.Read()
          Then
          ' A record has returned from the Stored Procedure
          ' The numbers in the GetInt32 / GetString methods refer to
          ' the position of the field. So, care must be taken to SELECT
          ' the fields in the same order in the stored procedure.
          details.strRecordId = dataReader.GetInt32(0)
          details.strAllowed= dataReader.GetInt32(1)
          details.strName = dataReader.GetString(2)
          details.strSurname = dataReader.GetString(3)
          details.strClass = dataReader.GetString(4)
          details.strEmail = dataReader.GetString(5)
          details.strUserName = dataReader.GetString(6)
          details.strPassword = dataReader.GetString(7)
          details.strSkin = dataReader.GetString(8)
          details.s

          1 Reply Last reply
          0
          • C Chodici Mrkev

            Thank you for your answer, you saved me for the second time :) When you help me with stored procedure last time, I decided to make more user-friendly interface - I decided to add possibility of editing of existing records - My idea was to make a function ReadUserData, which will be called in two cases: 1)During the editing 2)After successful registration to show all data again. So I created data structure that will be used to save of the data of edited user. Private Structure UserData Dim strRecordID As Integer Dim strAllowed As Integer Dim strName As String Dim strSurname As String Dim strClass As String Dim strEmail As String Dim strUsername As String Dim strPassword As String Dim strSkin As String Dim strImagePath As String End Structure What I want is to get the data from db to this structure, then I need to update it. I haven't a clue how to do it so I decided to try to make a function: ALTER FUNCTION dbo.Function1 ( @Username varchar(50) ) RETURNS TABLE AS RETURN ( SELECT * FROM Users WHERE Username = @Username) Although I don't know how to retrieve data from db, so I was thinking about something like: Dim cmd As New SqlClient.SqlCommand("RegisterUser", vilemConn) cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.Add("@Username", txtUsername.Text) cmd.Parameters.Add("@Password", inputPassword1.Value)but in the other way - to get the values of these parameters. Thanks a lot

            C Offline
            C Offline
            Colin Angus Mackay
            wrote on last edited by
            #5

            Okay - Now for part two: Inserting the data I've abbreviated the code here, because it gets a little repetative, you should get the idea. Create a stored procedure like this:

            CREATE PROCEDURE UpdateUserDetails(@RecordID int, @Allowed int, @Name varchar(64), @Surname varchar(64),
            @Class varchar(64), @Email varchar(64), @Username varchar(64), @Password varchar(64),
            @Skin varchar(64), @ImagePath varchar(64))
            AS

            -- Check to make sure the data exists already to be updated.
            IF EXISTS(SELECT * FROM Users WHERE UserName = @UserName AND Password = @Password)
            BEGIN
            -- Perform the update, all fields, except UserName and Password are updated here
            UPDATE Users
            SET Allowed = @Allowed, Name = @Name, Surname = @Surname -- and so on....
            WHERE UserName = @UserName AND Password = @Password
            END
            ELSE
            BEGIN
            -- THere is no existing data to be updated, Raise and error - This will cause
            -- a SqlException to be thrown in the .NET Application.
            RAISERROR('The User does not exist', 16, 1);
            -- Alternatively, an INSERT could be performed here.
            END
            GO

            In the .NET application you would write some code similar to this:

            Dim cmd As New SqlClient.SqlCommand("UpdateUserDetails", vilemConn)
            cmd.CommandType = CommandType.StoredProcedure
            cmd.Parameters.Add("@Username", details.strUserName)
            cmd.Parameters.Add("@Password", details.strPassword)
            ' Keep adding parameters until all the parameters that the stored procedure takes are in.
            ' For consistency the parameters should be in the same order they appear in the stored procedure
            ' definition.

            A final note. RecordId appears to be the Primary Key for the Users table. It is not a good idea to update that. It can cause all sorts of problems with Foreign Key relationships and depending on how you have your SQL Server set up it would most likely cause an error. Does this help?


            "If a man empties his purse into his head, no man can take it away from him, for an investment in knowledge pays the best interest." -- Joseph E. O'Donnell Not getting the response you want from a question asked in an online forum: How to Ask Questions the Smart Way!

            C 1 Reply Last reply
            0
            • C Colin Angus Mackay

              Okay - Now for part two: Inserting the data I've abbreviated the code here, because it gets a little repetative, you should get the idea. Create a stored procedure like this:

              CREATE PROCEDURE UpdateUserDetails(@RecordID int, @Allowed int, @Name varchar(64), @Surname varchar(64),
              @Class varchar(64), @Email varchar(64), @Username varchar(64), @Password varchar(64),
              @Skin varchar(64), @ImagePath varchar(64))
              AS

              -- Check to make sure the data exists already to be updated.
              IF EXISTS(SELECT * FROM Users WHERE UserName = @UserName AND Password = @Password)
              BEGIN
              -- Perform the update, all fields, except UserName and Password are updated here
              UPDATE Users
              SET Allowed = @Allowed, Name = @Name, Surname = @Surname -- and so on....
              WHERE UserName = @UserName AND Password = @Password
              END
              ELSE
              BEGIN
              -- THere is no existing data to be updated, Raise and error - This will cause
              -- a SqlException to be thrown in the .NET Application.
              RAISERROR('The User does not exist', 16, 1);
              -- Alternatively, an INSERT could be performed here.
              END
              GO

              In the .NET application you would write some code similar to this:

              Dim cmd As New SqlClient.SqlCommand("UpdateUserDetails", vilemConn)
              cmd.CommandType = CommandType.StoredProcedure
              cmd.Parameters.Add("@Username", details.strUserName)
              cmd.Parameters.Add("@Password", details.strPassword)
              ' Keep adding parameters until all the parameters that the stored procedure takes are in.
              ' For consistency the parameters should be in the same order they appear in the stored procedure
              ' definition.

              A final note. RecordId appears to be the Primary Key for the Users table. It is not a good idea to update that. It can cause all sorts of problems with Foreign Key relationships and depending on how you have your SQL Server set up it would most likely cause an error. Does this help?


              "If a man empties his purse into his head, no man can take it away from him, for an investment in knowledge pays the best interest." -- Joseph E. O'Donnell Not getting the response you want from a question asked in an online forum: How to Ask Questions the Smart Way!

              C Offline
              C Offline
              Chodici Mrkev
              wrote on last edited by
              #6

              You're a database genius, again thank you very much. I really regard all your help and the time you devoted to it. I wouldn't be able to continue in this project without you. The first part has just started working, I am going to try the second part (tomorrow, now I go to bed :)). At the end of the development I will publish the whole project in Code Project. Bye.

              C 1 Reply Last reply
              0
              • C Chodici Mrkev

                You're a database genius, again thank you very much. I really regard all your help and the time you devoted to it. I wouldn't be able to continue in this project without you. The first part has just started working, I am going to try the second part (tomorrow, now I go to bed :)). At the end of the development I will publish the whole project in Code Project. Bye.

                C Offline
                C Offline
                Colin Angus Mackay
                wrote on last edited by
                #7

                chodicimrkev wrote: You're a database genius Thanks. :-O Although I would like to just say that I've worked for over 12 years with various database systems and I am a firm believer that pratice makes perfect. :)


                "If a man empties his purse into his head, no man can take it away from him, for an investment in knowledge pays the best interest." -- Joseph E. O'Donnell Not getting the response you want from a question asked in an online forum: How to Ask Questions the Smart Way!

                1 Reply Last reply
                0
                Reply
                • Reply as topic
                Log in to reply
                • Oldest to Newest
                • Newest to Oldest
                • Most Votes


                • Login

                • Don't have an account? Register

                • Login or register to search.
                • First post
                  Last post
                0
                • Categories
                • Recent
                • Tags
                • Popular
                • World
                • Users
                • Groups