Solved

left innerjoin sql statement in vb.net

Posted on 2014-09-30
16
153 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
  • 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 33

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
Best Practices: Disaster Recovery Testing

Besides backup, any IT division should have a disaster recovery plan. You will find a few tips below relating to the development of such a plan and to what issues one should pay special attention in the course of backup planning.

 

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

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

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

Slowly Changing Dimension Transformation component in data task flow is very useful for us to manage and control how data changes in SSIS.
Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
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…
Using examples as well as descriptions, and references to Books Online, show the documentation available for datatypes, explain the available data types and show how data can be passed into and out of variables.

809 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