I got this little code where I connect to a db, select the data and write the data to a file.
...
sqlquery = ("select field1 as Asl, field2 as nCuen , field3 as nfac , "" as contr from [2016cl]")
Using connection As SqlConnection = New SqlConnection("server=" & srvSQL & ";database=" & bdSQL & ";uid=" & usrSQL & ";password=" & pswSQL & ";")
connection.Open()
Using comm As SqlCommand = New SqlCommand(sqlquery, connection)
Dim rs As SqlDataReader = comm.ExecuteReader
Dim dt As DataTable = New DataTable
dt.Load(rs)
Call clCreateCSV.CreateCSVFile(dt, strFileNameDiario)
End Using
connection.Close()
End Using
.....
Public Shared Sub CreateCSVFile(dt As DataTable, strFilePath As String)
Dim sw As New StreamWriter(strFilePath, False, Encoding.UTF8)
Dim iColCount As Integer = dt.Columns.Count
For Each dr As DataRow In dt.Rows
For i As Integer = 0 To iColCount - 1
If Not Convert.IsDBNull(dr(i)) Then
sw.Write(dr(i).ToString())
End If
If i < iColCount - 1 Then
sw.Write(";")
End If
Next
sw.Write(sw.NewLine)
Next
sw.Close()
End Sub
I need to fill 4th value on the select ("" as contr) with field from another table which joins to another middle table.
field3 joins another table on GFac.Gfac2
the table Gfac joins the 3rd table on CCli.ccli1 --> this is the one I need on the query
Could just use inner join but, afaik it would only get the fields that validate the join.
how can i do this, writing ALL the data from [2016cl] and the field contr for each one of them if it exists?
Thanks in advance. If you need more info, just ask!
Use LEFT JOIN instead INNER JOIN.
For example:
SELECT * FROM TABLE1 LEFT JOIN TABLE2 ON ...
That query selects ALL rows from TABLE1. If a row in TABLE1 doesn't have a match record in TABLE2, then the TABLE2 fields contains NULL.
Hope that helps.
Related
I wanted to do the sql command "select DISTINCT" but it didn't work if there was another solution. I have four tables namely GSDTS, GSGTS, STFTS and TEMPTABL.
Thanks
error
Private Sub PopulateComboBox()
Dim query As String = "SELECT DISTINCT PNM FROM GSDTS"
Try
Using con As OleDbConnection = New OleDbConnection(cn)
Using sda As OleDbDataAdapter = New OleDbDataAdapter(query, con)
'Fill the DataTable with records from Table.
Dim dt As DataTable = New DataTable()
sda.Fill(dt)
'Insert the Default Item to DataTable.
Dim row As DataRow = dt.NewRow()
row(0) = ""
dt.Rows.InsertAt(row, 0)
'Assign DataTable as DataSource
ComboBox1.DataSource = dt
ComboBox1.DisplayMember = "PNM"
ComboBox1.ValueMember = "PNM"
End Using
End Using
Catch myerror As OleDbException
MessageBox.Show("Error: " & myerror.Message)
Finally
End Try
End Sub
you neeed to cnage the query to
SELECT DISTINCT PNM FROM GSDTS
UNION
SELECT DISTINCT PNM FROM GSGTS
UNION
SELECT DISTINCT PNM FROM STFTS
UNION
SELECT DISTINCT PNM FROM TEMPTAB
ORDER BY PNM
the DISINCT will only take UNIQUE OMN and the UNION will take care of all duplicates.
But you will so never know,. which PMN belongs to which table.
I am currently working in Microsoft Visual Studio Express 2013 with a SQL Server back end. I am using a SQL query to pull a datatable and then selecting the first cell to pull a number from. I need to take this number from the datatable and then change a label to show this number as either a 2 decimal number or a percentage would be even better. Here is my code:
Try
Dim Associates As Integer = NUPAssociates.Value
Dim Hours As Integer = NUPHours.Value
Dim WorkingHours As Integer = (Associates * Hours)
' MsgBox(WorkingHours)
'sql connection
Using conn1 As New SqlConnection(connstring)
conn1.Open()
Using comm1 As New SqlCommand("SELECT ((sum([Time])/60)/#WorkHours) as EarnedHours FROM table1 " _
& "Left Join table2 on table1.PartNumber + '-' = table2.PART_NUMBER " _
& "WHERE col1 >= #start AND col1 < dateadd(day, 1, #Start) " _
& "AND col2 = 25 AND col3 = 1 AND FloorNumber is not null and col4 > 30", conn1)
comm1.Parameters.AddWithValue("#Start", DTPStart.Value.ToString("yyyy-MM-dd"))
comm1.Parameters.AddWithValue("#WorkHours", WorkingHours)
Dim dt As New DataTable
Dim sql As New SqlDataAdapter(comm1)
sql.Fill(dt)
Dim EFF As String = dt.Rows(0).Item(0).value.ToString("N2")
labeleff.Text = EFF
End Using
conn1.Close()
End Using
Catch ex As Exception
MsgBox(ex.ToString)
End Try
You're trying to access the value in the datatable cell with
dt.Rows(0).Item(0).value.ToString("N2")
but dt.Rows(0).Item(0) (or simply dt.Rows(0)(0)) already return the value as an object. You use value property to retrieve the value from a DataGridViewCell.
The "right" way to do it would be:
CDbl(dt.Rows(0)(0)).ToString("N2")
My problem is, in one button (click event) I need to Copy a data in Table1 (the ToolName) to Table2 (into ToolName) and insert a description to the same row.
Table1
ID - ToolName - Quantity
Table2
ID - ToolName - Description
here`s my codes
Dim sqlquery As String = "INSERT INTO Table2 (ToolName) SELECT ToolName FROM Table1 WHERE ID = '" & DataGridView1.CurrentRow.Cells(0).Value.ToString & "' INSERT INTO Table2 (Description) VALUES ('" & TextBox1.Text & "')"
Dim cmd As New OleDbCommand(sqlquery, con)
con.Open()
cmd.ExecuteNonQuery()
MsgBox(" succesfully", vbInformation)
con.Close()
Parametrized queries have two main advantages:
Security: It is a good way to avoid SQL Injection vulnerabilities
Performance: If you regularly invoke the same query just with different parameters a parametrized query might allow the database to cache your queries which is a considerable source of performance gain.
Extra: You won't have to worry about date and time formatting issues in your database code. Similarly, if your code will ever run on machines with a non-English locale, you will not have problems with decimal points / decimal commas.
Try like this
Dim sqlquery As String= "INSERT INTO Table2 (ToolName,Descrption) SELECT ToolName,#Desc FROM Table1 WHERE ID = #Id"
Dim cmd As New OleDbCommand(sqlquery, con)
cmd.Parameters.Add("#Desc", SqlDbType.VarChar, 50).Value = TextBox1.Text
cmd.Parameters.Add("#Id", SqlDbType.VarChar, 50).Value = DataGridView1.CurrentRow.Cells(0).Value.ToString
con.Open()
cmd.ExecuteNonQuery()
MsgBox("succesfully", vbInformation)
con.Close()
Change Query syntax like below
Dim sqlquery As String = "INSERT INTO Table2 (ToolName)
SELECT ToolName FROM Table1
WHERE ID = '" & DataGridView1.CurrentRow.Cells(0).Value.ToString & "';
INSERT INTO Table2 (Description) VALUES ('" & TextBox1.Text & "')"
I think nothing is wrong in query just missing ; between 2 insert query.
Just break it down into two separate updates based on what you already have, use the following code and just pass the ToolName into your update statements
Dim Table_ As String = "getToolName"
Dim query As String = "SELECT ToolName FROM Table1 WHERE ID = '" & DataGridView1.CurrentRow.Cells(0).Value.ToString
Dim cmd As New OleDbCommand(query, con)
Dim da As New OleDbDataAdapter(cmd)
da.Fill(ds, Table_)
Dim dt As DataTable = ds.Tables(Table_)
Dim ToolName As String = dt.Rows(0)(0).ToString()
I have 2 tables, products, and author, the author table has a column that relates to the product table by an ID so I have done a select statement below to get the right rows based on the ID's. However the author table might not have any data in and therefore no ID to the product table. If this is the case then the information from the product doesn't show up.
So my question is how do i handle this?
Dim ID As String = Request("id")
If String.IsNullOrEmpty(ID) Then
Response.Redirect("/Default.aspx")
End If
Try
Using conn As New OleDbConnection(strcon)
conn.Open()
Dim cmd As String = "SELECT * FROM tblProducts, tblPrdAuthor " & _
"WHERE tblProducts.ID = " & ID & " AND tblPrdAuthor.paPrdID = tblProducts.ID"
Using da As New OleDbDataAdapter(cmd, conn)
Dim ds As New DataSet()
da.Fill(ds)
'Bind to the repeater
rptProduct.DataSource = ds
rptProduct.DataBind()
End Using
End Using
Catch ex As Exception
Throw ex
End Try
Thank you!
Select * from table1 as A left outer join table2 as B on (A.id=B.id) where a.id=101 and b.pid=102
I have the following code:
Imports System.Data
Imports System.Data.OleDb
Partial Class Dummy
Inherits System.Web.UI.Page
Dim r As OleDbDataReader
Dim con As OleDb.OleDbConnection
Dim cmd As OleDbCommand
Dim cmd1 As OleDbCommand
Dim prev_ob As New List(Of Int64)
Dim cur_ob As Integer
Dim i As Integer = 0
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
con = New OleDb.OleDbConnection("provider=SQLOLEDB;data source=PC;initial catalog=DB1;integrated security=SSPI")
cmd = New OleDbCommand("select single_column from table1 where date_reqd=(SELECT CONVERT(VARCHAR(10),DATEADD(DD, DATEDIFF(DD, 0, GETDATE()), -1),120))", con)
con.Open()
r = cmd.ExecuteReader
While r.Read
prev_ob.Add(Val(r.Item(0)))
End While
cmd = New OleDbCommand("select column1, column2, date_reqd from table1 where date_reqd=(select CONVERT(varchar(10), GETDATE(),120))", con)
r = cmd.ExecuteReader
While r.Read
For i As Integer = 0 To prev_ob.Count - 1
cur_ob = Val(prev_ob(i)) + Val(r.Item(0))
cmd1 = New OleDbCommand("update table1 set column4='" & cur_ob & "' where column2='" & r.Item(1) & "' and date_reqd='" & r.Item(2) & "'", con)
cmd1.ExecuteNonQuery()
i += 1
Exit For
Next
End While
con.Close()
End Sub
End Class
The problem I'm facing is that the update happens correctly only for the first of many values. All the other values are calculated and consequently, updated incorrectly in my table. I am almost certain that the looping is what is causing the problem but have been unable to find a way around it. Please help me correct it.
It looks like this should be a single UPDATE statement. Unfortunately, it's tricky to tell without seeing your actual table structure. First, write a select statement like this (I'm hoping date_reqd is actually a datetime column also):
SELECT
*
FROM
table1 t1a
inner join
table1 t1b
on
t1a.date_reqd = DATEADD(day,DATEDIFF(day,0,CURRENT_TIMESTAMP),-1) and
t1b.date_reqd = DATEADD(day,DATEDIFF(day,0,CURRENT_TIMESTAMP),0) and
/* You need other conditions here if there are multiple rows for the same dates
- I'm guessing there are since you're trying to write a loop */
Once you have this query working, remove the first two lines (SELECT *), and replace them with:
UPDATE
t1b
SET
column4 = t1a.single_column + t1b.column1
And you should be done.
I got it myself! :) All I needed to do was:
Dim i as Integer=0
While r.Read
cur_ob = Val(prev_ob(i)) + Val(r.Item(0))
cmd1 = New OleDbCommand("update table1 set column4='" & cur_ob & "' where column2='" & r.Item(1) & "' and date_reqd='" & r.Item(2) & "'", con)
cmd1.ExecuteNonQuery()
cur_ob = 0
i += 1
End While
And it worked! Thanks for your answers/comments and #Damien_The_Unbeliever, I changed my primary queries to include an ORDER BY clause. Thanks for the tip! :)