Solved

left innerjoin sql statement in vb.net

Posted on 2014-09-30
16
164 Views
Last Modified: 2014-10-02
Hey I need to create I guess it's called a Left innerjoin allow me to match a PlayerID on one table called NflPlayers and PlayerID on a second main table called NFLPlayersPass then take firstname  + Lastname in hopefully one datagridview cell but if it can't be done then firstname one cell and then lastname next cell here is the main table code
 Public Sub GetpassingNfl()
        Dim sql As String
        connetionString = "Data Source=tsnappdev01;Initial Catalog=TSN2;User ID=sa;Password=sportsrus"
        sql = "Select PlayerID,Team,Season,Seasontype,Conference,Att,Comp,Yards,Long,TD,Inter,Sacks,SKYds,Rating FROM NFLPlayersPass WHERE PlayerID=" & PlayerID2 & "Order By Season desc"

        dvgPass.DataSource = Nothing
        dvgPass.ClearSelection()



        connection = New SqlConnection(connetionString)
        Dim ds As New DataSet

        Try
            connection.Open()
            adapter = New SqlDataAdapter(sql, connection)
            adapter.Fill(ds)
            connection.Close()
            dvgPass.DataSource = ds.Tables(0)

        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try

        ' ds.Tables(Currentrow) = "Lastname" = txtLname.Text
        ' ds.Tables(Currentrow).Column("College") = txtCollege.Text

        ' txtLname.Text = ds.Tables(Currentrow).TableName("Lastname")
        ' txtCollege.Text = ds.Tables(Currentrow).Item("College")

        Me.dvgPass.RowsDefaultCellStyle.BackColor = Color.Bisque
        Me.dvgPass.AlternatingRowsDefaultCellStyle.BackColor = Color.Beige
        dvgPass.ColumnHeadersHeight = 55
        dvgPass.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize
        ' Add the image column to the grid.
        ' DataGridView1.Columns.Add(imageCol)

        '  DataGridView1.Columns("Lastname").Frozen = False
        ' dvgPass.Columns("SeasonType").Frozen = True
    End Sub

Open in new window

Thanks EE
0
Comment
Question by:powerztom
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 10
  • 5
16 Comments
 
LVL 40

Expert Comment

by:Kyle Abrahams
ID: 40352320
Note that in the current form your code is subject to sql injection.

Imagine if playerID2 were to read "1; drop table nflplayers; --"

The way around this is to parameterize the value.  Your join is included.  Note you may need to alias each column if the column names exist in both.  You can bind to "fullName" in your datagrid.
"Select np.PlayerID,Team,Season,Seasontype,Conference,Att,Comp,Yards,Long,TD,Inter,Sacks,SKYds,Rating,
FirstName + ' ' + LastName as FullName
FROM 
NflPlayers np
join NFLPlayersPass npp on np.PlayerId = npp.PlayerID
WHERE np.PlayerID= @PlayerID Order By Season desc"


SqlDataAdapter.SelectCommand.AddParameterWithValue("@playerID", PlayerID2 )

Open in new window

0
 
LVL 34

Expert Comment

by:ste5an
ID: 40352347
Use your SQL Server. Create the JOIN as view or stored procedure.
0
 

Author Comment

by:powerztom
ID: 40352557
STE5AN I would love to but I don't know how I'm trying Klye Abrams code I got a sql error near the where clause see screen shot. and thanks for heads up on sql injection but when I setup mySQLDataAdapter As New SqlDataAdapter and SelectCommand As New SqlCommand I get a blue line under
mySQLDataAdapter.SelectCommand.AddParameterWithValue("@playerID", PlayerID2) Any Suggestions

 Public Sub GetpassingNfl()
        Dim sql As String
        Dim mySQLDataAdapter As New SqlDataAdapter
        Dim SelectCommand As New SqlCommand
        connetionString = "Data Source=tsnappdev01;Initial Catalog=TSN2;User ID=sa;Password=sportsrus"
        sql = "Select np.PlayerID,Team,Season,Seasontype,Conference,Att,Comp,Yards,Long,TD,Inter,Sacks,SKYds,Rating,FirstName + ' ' + LastName as FullName FROM() NflPlayers np"
        sql = "join NFLPlayersPass npp on np.PlayerId = npp.PlayerID"
        sql = "WHERE np.PlayerID= @PlayerID Order By Season desc"


        ' mySQLDataAdapter.SelectCommand.AddParameterWithValue("@playerID", PlayerID2)

        dvgPass.DataSource = Nothing
        dvgPass.ClearSelection()



        connection = New SqlConnection(connetionString)
        Dim ds As New DataSet

        Try
            connection.Open()
            adapter = New SqlDataAdapter(sql, connection)
            adapter.Fill(ds)
            connection.Close()
            dvgPass.DataSource = ds.Tables(0)

        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try

        ' ds.Tables(Currentrow) = "Lastname" = txtLname.Text
        ' ds.Tables(Currentrow).Column("College") = txtCollege.Text

        ' txtLname.Text = ds.Tables(Currentrow).TableName("Lastname")
        ' txtCollege.Text = ds.Tables(Currentrow).Item("College")

        Me.dvgPass.RowsDefaultCellStyle.BackColor = Color.Bisque
        Me.dvgPass.AlternatingRowsDefaultCellStyle.BackColor = Color.Beige
        dvgPass.ColumnHeadersHeight = 55
        dvgPass.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize
        ' Add the image column to the grid.
        ' DataGridView1.Columns.Add(imageCol)

        '  DataGridView1.Columns("Lastname").Frozen = False
        ' dvgPass.Columns("SeasonType").Frozen = True
    End Sub

Open in new window

0
The Ultimate Checklist to Optimize Your Website

Websites are getting bigger and complicated by the day. Video, images, custom fonts are all great for showcasing your product/service. But the price to pay in terms of reduced page load times and ultimately, decreased sales, can lead to some difficult decisions about what to cut.

 

Author Comment

by:powerztom
ID: 40352652
Forgot this is the error I'm recieving Kyle
0
 

Author Comment

by:powerztom
ID: 40352817
Kyle what does np and npp mean in your select statement?
0
 
LVL 40

Expert Comment

by:Kyle Abrahams
ID: 40353080
Remove the parentheses () here:
FROM() NflPlayers np

What I'm doing is aliasing the tables.

so basically np means NFLplayers
and npp means NFLPlayersPass
0
 

Author Comment

by:powerztom
ID: 40353164
i'M STILL GETTING SAME ERROR MESSAGE ABOUT THE INNCORRECT SYNTAX NEAR THE WHERE CLAUSE DO I HAVE A ODD  CHARACTER ALSO i REMMED OUT
 mySQLDataAdapter.SelectCommand.AddParameterWithValue("@playerID", PlayerID2) COULD IT BE THAT CAUSE THIS LINE WAS GIVING ME AND ERROR LINE UNDER  IT.
0
 

Author Comment

by:powerztom
ID: 40353166
Public Sub GetpassingNfl()
        Dim sql As String
        Dim mySQLDataAdapter As New SqlDataAdapter
        Dim SelectCommand As New SqlCommand
        connetionString = "Data Source=tsnappdev01;Initial Catalog=TSN2;User ID=sa;Password=sportsrus"
        sql = "Select np.PlayerID,Team,Season,Seasontype,Conference,Att,Comp,Yards,Long,TD,Inter,Sacks,SKYds,Rating,FirstName + ' ' + LastName as FullName FROM NflPlayers np"
        sql = "join NFLPlayersPass npp on np.PlayerId = npp.PlayerID"
        sql = "WHERE np.PlayerID= @PlayerID Order By Season desc"


        ' mySQLDataAdapter.SelectCommand.AddParameterWithValue("@playerID", PlayerID2)

        dvgPass.DataSource = Nothing
        dvgPass.ClearSelection()



        connection = New SqlConnection(connetionString)
        Dim ds As New DataSet

        Try
            connection.Open()
            adapter = New SqlDataAdapter(sql, connection)
            adapter.Fill(ds)
            connection.Close()
            dvgPass.DataSource = ds.Tables(0)

        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try

        ' ds.Tables(Currentrow) = "Lastname" = txtLname.Text
        ' ds.Tables(Currentrow).Column("College") = txtCollege.Text

        ' txtLname.Text = ds.Tables(Currentrow).TableName("Lastname")
        ' txtCollege.Text = ds.Tables(Currentrow).Item("College")

        Me.dvgPass.RowsDefaultCellStyle.BackColor = Color.Bisque
        Me.dvgPass.AlternatingRowsDefaultCellStyle.BackColor = Color.Beige
        dvgPass.ColumnHeadersHeight = 55
        dvgPass.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize
        ' Add the image column to the grid.
        ' DataGridView1.Columns.Add(imageCol)

        '  DataGridView1.Columns("Lastname").Frozen = False
        ' dvgPass.Columns("SeasonType").Frozen = True
    End Sub

Open in new window

0
 
LVL 40

Expert Comment

by:Kyle Abrahams
ID: 40353488
   sql = "Select np.PlayerID,Team,Season,Seasontype,Conference,Att,Comp,Yards,Long,TD,Inter,Sacks,SKYds,Rating,FirstName + ' ' + LastName as FullName FROM NflPlayers np"
        sql += " join NFLPlayersPass npp on np.PlayerId = npp.PlayerID"
        sql += " WHERE np.PlayerID= @PlayerID Order By Season desc"

Open in new window


you need to append the statement, and you need to allow for spaces.
0
 

Author Comment

by:powerztom
ID: 40354724
Kyle  a few things npp represents the stats PlayerID,Team,Season,Seasontype,Conference,Att,Comp,Yards,Long,TD,Inter,Sacks,SKYds,Rating
and np has FirstName + ' ' + LastName as FullName just grabbing name.
is that screwing up query cause there backwards.
And can I have it appear Fullname first in Datagridview?
here is the code

Imports System.Data
Imports System.Data.SqlClient
Public Class frmPASS
    Dim PlayerID2 As Integer
    Dim Position2 As String
    Public connetionString As String
    Dim connection As SqlConnection
    Dim adapter As SqlDataAdapter
    'Public da As SqlDataAdapter

    Public stgPath As String = "\\tsnfps01\webdev\branding\tompowers\Nflplayers\players\"
    Public stgPathTeam As String = "http://images.sportsnetwork.com/nfl/atthegridiron/Resources/"

    Public Sub GetpassingNfl()
        Dim sql As String
        Dim ds As New DataSet
        Dim da As New SqlDataAdapter
        connetionString = "Data Source=tsnappdev01;Initial Catalog=TSN2;User ID=sa;Password=sportsrus"
        connection = New SqlConnection(connetionString)
        sql = "Select np.PlayerID,Team,Season,Seasontype,Conference,Att,Comp,Yards,Long,TD,Inter,Sacks,SKYds,Rating,FirstName + ' ' + LastName as FullName FROM NflPlayers np"
        sql += "join NFLPlayersPass npp on np.PlayerID = npp.PlayerID"
        sql += "WHERE np.PlayerID= @PlayerID Order By Season desc"
        Dim SelectCommand As New SqlCommand(sql, connection)
        da.SelectCommand.Parameters.AddWithValue("@PlayerID", PlayerID2)
        
            Try
                connection.Open()
                adapter = New SqlDataAdapter(sql, connection)
                adapter.Fill(ds)
                connection.Close()
                dvgPass.DataSource = ds.Tables(0)

            Catch ex As Exception
                MsgBox(ex.ToString)
            End Try

            ' ds.Tables(Currentrow) = "Lastname" = txtLname.Text
            ' ds.Tables(Currentrow).Column("College") = txtCollege.Text

            ' txtLname.Text = ds.Tables(Currentrow).TableName("Lastname")
            ' txtCollege.Text = ds.Tables(Currentrow).Item("College")

            Me.dvgPass.RowsDefaultCellStyle.BackColor = Color.Bisque
            Me.dvgPass.AlternatingRowsDefaultCellStyle.BackColor = Color.Beige
            dvgPass.ColumnHeadersHeight = 55
            dvgPass.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize
            ' Add the image column to the grid.
            ' DataGridView1.Columns.Add(imageCol)

            '  DataGridView1.Columns("Lastname").Frozen = False
            ' DataGridView1.Columns("Lastname").Frozen = True



        ' dvgPass.DataSource = Nothing
        ' dvgPass.ClearSelection()



           
            ' ds.Tables(Currentrow) = "Lastname" = txtLname.Text
            ' ds.Tables(Currentrow).Column("College") = txtCollege.Text

            ' txtLname.Text = ds.Tables(Currentrow).TableName("Lastname")
            ' txtCollege.Text = ds.Tables(Currentrow).Item("College")

            Me.dvgPass.RowsDefaultCellStyle.BackColor = Color.Bisque
            Me.dvgPass.AlternatingRowsDefaultCellStyle.BackColor = Color.Beige
            dvgPass.ColumnHeadersHeight = 55
            dvgPass.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize
            ' Add the image column to the grid.
            ' DataGridView1.Columns.Add(imageCol)

            '  DataGridView1.Columns("Lastname").Frozen = False
            dvgPass.Columns("SeasonType").Frozen = True
    End Sub









   
    Private Sub frmPASS_Load(sender As Object, e As EventArgs) Handles Me.Load
        lblName.Text = Form1.txtFname.Text & Form1.txtLname.Text & Form1.txtPosition.Text
        PlayerID2 = CInt(Form1.Playerid1)
        Position2 = Form1.txtPosition.Text

        GetpassingNfl()
        
    End Sub

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        picplayer.ImageLocation = Form1.stgPath & Form1.txtPlayerID.Text & ".jpg"
        picTeam.ImageLocation = Form1.stgPathTeam & Form1.txtTeamID.Text & ".png"
    End Sub
End Class[embed=file 875247]

Open in new window

Kyle thanks for your help so far.
Sqlexception.png
0
 

Author Comment

by:powerztom
ID: 40354739
Actually it just hangs if aI rem out
 da.SelectCommand.Parameters.AddWithValue("@PlayerID", PlayerID2) set a breakpoint on this line and PlayerID2 HAD THE CORRECT PlayerID. ANY SUGGESTIONS i COULD SURE USE IT.
0
 
LVL 40

Expert Comment

by:Kyle Abrahams
ID: 40354773
sql = "Select np.PlayerID,Team,Season,Seasontype,Conference,Att,Comp,Yards,Long,TD,Inter,Sacks,SKYds,Rating,FirstName + ' ' + LastName as FullName FROM NflPlayers np"
        sql += "[SPACE HERE] join NFLPlayersPass npp on np.PlayerID = npp.PlayerID"
        sql += "[SPACE HERE] WHERE np.PlayerID= @PlayerID Order By Season desc"



 sql = "Select np.PlayerID,Team,Season,Seasontype,Conference,Att,Comp,Yards,Long,TD,Inter,Sacks,SKYds,Rating,FirstName + ' ' + LastName as FullName FROM NflPlayers np"
        sql += " join NFLPlayersPass npp on np.PlayerID = npp.PlayerID"
        sql += " WHERE np.PlayerID= @PlayerID Order By Season desc"

Open in new window

0
 

Author Comment

by:powerztom
ID: 40355616
kYLE MY FRIEND This has been a battle I was getting @PLayer SQLexception error then I added the parameterized query now It just Freezes for like five seconds then Terminates no SQL Error Message.
here is code which I'm sure something I did not your code
Imports System.Data
Imports System.Data.SqlClient
Public Class frmPASS
    Dim PlayerID2 As Integer
    Dim Position2 As String
    Public connetionString As String
    Dim connection As SqlConnection
    Dim adapter As SqlDataAdapter
    'Public da As SqlDataAdapter

    Public stgPath As String = "\\tsnfps01\webdev\branding\tompowers\Nflplayers\players\"
    Public stgPathTeam As String = "http://images.sportsnetwork.com/nfl/atthegridiron/Resources/"

    Public Sub GetpassingNfl()
        Dim sql As String
        Dim ds As New DataSet
        Dim mySQLDATAAdapter As New SqlDataAdapter
        Dim SelectCommand As New SqlCommand
        ' Dim da As New SqlDataAdapter
        connetionString = "Data Source=tsnappdev01;Initial Catalog=TSN2;User ID=sa;Password=sportsrus"
        connection = New SqlConnection(connetionString)
        mySQLDATAAdapter.SelectCommand.Parameters.AddWithValue("@PlayerID", PlayerID2)
        sql = "Select np.PlayerID,Team,Season,Seasontype,Conference,Att,Comp,Yards,Long,TD,Inter,Sacks,SKYds,Rating,FirstName + ' ' + LastName as FullName FROM NflPlayers np"
        sql += " join NFLPlayersPass npp on np.PlayerID = npp.PlayerID"
        sql += " WHERE np.PlayerID= @PlayerID Order By Season desc"

        '  sql = "Select PlayerID,Team,Season,Seasontype,Conference,Att,Comp,Yards,Long,TD,Inter,Sacks,SKYds,Rating FROM NflPlayersPass"

        ' sql += " WHERE PlayerID=" & PlayerID2 & "Order By Season desc"
        
        
            Try
                connection.Open()
                adapter = New SqlDataAdapter(sql, connection)
                adapter.Fill(ds)
                connection.Close()
                dvgPass.DataSource = ds.Tables(0)

        Catch ex As SqlException
            MsgBox(ex.ToString)
            End Try

            ' ds.Tables(Currentrow) = "Lastname" = txtLname.Text
            ' ds.Tables(Currentrow).Column("College") = txtCollege.Text

            ' txtLname.Text = ds.Tables(Currentrow).TableName("Lastname")
            ' txtCollege.Text = ds.Tables(Currentrow).Item("College")

            Me.dvgPass.RowsDefaultCellStyle.BackColor = Color.Bisque
            Me.dvgPass.AlternatingRowsDefaultCellStyle.BackColor = Color.Beige
            dvgPass.ColumnHeadersHeight = 55
            dvgPass.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize
            ' Add the image column to the grid.
            ' DataGridView1.Columns.Add(imageCol)

            '  DataGridView1.Columns("Lastname").Frozen = False
            ' DataGridView1.Columns("Lastname").Frozen = True



        ' dvgPass.DataSource = Nothing
        ' dvgPass.ClearSelection()



           
            ' ds.Tables(Currentrow) = "Lastname" = txtLname.Text
            ' ds.Tables(Currentrow).Column("College") = txtCollege.Text

            ' txtLname.Text = ds.Tables(Currentrow).TableName("Lastname")
            ' txtCollege.Text = ds.Tables(Currentrow).Item("College")

            Me.dvgPass.RowsDefaultCellStyle.BackColor = Color.Bisque
            Me.dvgPass.AlternatingRowsDefaultCellStyle.BackColor = Color.Beige
            dvgPass.ColumnHeadersHeight = 55
            dvgPass.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize
            ' Add the image column to the grid.
            ' DataGridView1.Columns.Add(imageCol)

            '  DataGridView1.Columns("Lastname").Frozen = False
            dvgPass.Columns("SeasonType").Frozen = True
    End Sub









   
    Private Sub frmPASS_Load(sender As Object, e As EventArgs) Handles Me.Load
        lblName.Text = Form1.txtFname.Text & Form1.txtLname.Text & Form1.txtPosition.Text
        PlayerID2 = CInt(Form1.Playerid1)
        Position2 = Form1.txtPosition.Text

        GetpassingNfl()
        
    End Sub

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        picplayer.ImageLocation = Form1.stgPath & Form1.txtPlayerID.Text & ".jpg"
        picTeam.ImageLocation = Form1.stgPathTeam & Form1.txtTeamID.Text & ".png"
    End Sub

    Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExitToolStripMenuItem.Click
        Me.Close()


    End Sub
End Class

Open in new window

Kyle I truely appreciates your efforts cause I need to do this join in more forms
0
 
LVL 40

Accepted Solution

by:
Kyle Abrahams earned 500 total points
ID: 40355873
You're using adapter to fill . . . you need to add the parameter to adapter to get it to work right:

  adapter = New SqlDataAdapter(sql, connection)
  adapter.SelectCommand.Parameters.AddWithValue("@PlayerID", PlayerID2)
  adapter.Fill(ds)
0
 

Author Closing Comment

by:powerztom
ID: 40356934
Kyle you are awesome. I know I've make novice mistakes and you are patience enough to continue to help. I saw your work history. You are a God when it comes to this. Thank You my Friend.
0
 

Author Comment

by:powerztom
ID: 40357069
Kyle everything is great but I found one thing I screwed up I should have noticed. So I'm gonna put in a new ticket. Joining one more table with a field I need.
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

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.
Ever wondered why sometimes your SQL Server is slow or unresponsive with connections spiking up but by the time you go in, all is well? The following article will show you how to install and configure a SQL job that will send you email alerts includ…
Familiarize people with the process of utilizing SQL Server functions from within Microsoft Access. Microsoft Access is a very powerful client/server development tool. One of the SQL Server objects that you can interact with from within Microsoft Ac…
Via a live example combined with referencing Books Online, show some of the information that can be extracted from the Catalog Views in SQL Server.

688 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