Solved

Populate VB.net variables from SQL Select Query

Posted on 2013-11-27
3
729 Views
Last Modified: 2013-11-27
I am calling this sql command from vb.net:

cmd.CommandText = "SELECT * FROM SNUGZ_EXT00101_SOP10200_2 WHERE PT_UD_KEY = '" & strKey & "'"
       
The sql query will return 1 row with several columns labeled PT_UD_1, PT_UD_2, etc.

I want to put the values in the columns into variables in my vb.net code.  For example:

strImprint = PT_UD_1
strImprintColor = PT_UD_2


How do I code my vb.net to do this?
0
Comment
Question by:thoecherl
  • 2
3 Comments
 

Author Comment

by:thoecherl
Comment Utility
Additional information:

I only want to run the SQL query once.  I don't want to run it each time for each of the 12 variables I need to populate.
0
 
LVL 74

Accepted Solution

by:
käµfm³d   👽 earned 500 total points
Comment Utility
Use the ExecuteReader method of your command object.

e.g.

Dim reader As SqlDataReader = cmd.ExecuteReader()

If reader.Read() Then  ' If there is at least one row
    strImprint = reader("PT_UD_1").ToString()
    strImprintColor = reader("PT_UD_2").ToString()
End If

Open in new window


Also be aware that your query is susceptible to SQL Injection. Building SQL queries using string concatenation is a bad practice. I suggest reading up on parameterized queries.
0
 

Author Closing Comment

by:thoecherl
Comment Utility
Did the trick.  Thanks.
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

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.
Slowly Changing Dimension Transformation component in data task flow is very useful for us to manage and control how data changes in SSIS.
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties
Viewers will learn how to use the SELECT statement in SQL to return specific rows and columns, with various degrees of sorting and limits in place.

744 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

15 Experts available now in Live!

Get 1:1 Help Now