Solved

VB.net SQL make sure only single value returned

Posted on 2014-03-12
2
224 Views
Last Modified: 2014-03-13
Hi. I am using the following code to pull a single result from a SQL table.
I need a way to check if the result returns more than one value first.
Is there a way to build that into this code? If not what code would I need
to run first to see if there is a single value returned for this SQL statement

                Dim connection As New SqlConnection(oConnectionString)
                Dim cmd As New SqlCommand(sSQL, connection)
                connection.Open()
                oResult = cmd.ExecuteScalar.ToString
                If IsDBNull(oResult) = True Then
                    Get_Value = "Null"
                Else
                    Get_Value = oResult
                End If
                connection.Close()
0
Comment
Question by:murbro
2 Comments
 
LVL 44

Accepted Solution

by:
AndyAinscow earned 500 total points
ID: 39925689
Assuming your SQL command doesn't have something such TOP 1 (to force maximum one row being returned in the query) you would need to use a reader:
http://msdn.microsoft.com/en-us/library/9kcbe65k%28v=vs.110%29.aspx

Instead of the ExecuteScalar you would use ExecuteReader.  Store the result from the first returned row if any and then check if there was a second row to see if more than one row was returned.
0
 

Author Closing Comment

by:murbro
ID: 39925782
Thanks very much
0

Featured Post

NAS Cloud Backup Strategies

This article explains backup scenarios when using network storage. We review the so-called “3-2-1 strategy” and summarize the methods you can use to send NAS data to the cloud

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
This video shows how to set up a shell script to accept a positional parameter when called, pass that to a SQL script, accept the output from the statement back and then manipulate it in the Shell.
Via a live example, show how to set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.

864 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now