I am trying to find a way to dynamically determine/reference a table name based on a value in another table.
In concept this is what I want:
SELECT * FROM TTestCase
WHERE TTestCase.ElementNo = (
SELECT TControlTables.ControlTable from TControlTables
WHERE TControlTables.MessageType in (
SELECT TTestCaseParameter.MessageType
FROM TTestCaseParameter).ElementNo
The "SELECT TControlTables.ControlTable from TControlTables
WHERE TControlTables.MessageType in (SELECT TTestCaseParameter.MessageType FROM TTestCaseParameter" is the query that determines which table's ElementNo should be compared with the TestCase.ElementNo.
Some very rough notes, you will get much better code here http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbcommand(v=vs.71).aspx. Hopefully, this will start you off.
Dim tablename As String
Dim cn As New OleDbConnection("connection here")
cn.Open()
Dim query = "SELECT TControlTables.ControlTable " _
& "FROM TControlTables " _
& "WHERE TControlTables.MessageType in ( " _
& "SELECT TTestCaseParameter.MessageType " _
& "FROM TTestCaseParameter)"
Dim dc = New OleDbCommand(query, cn)
Dim tname As OleDb.OleDbDataReader
tname = dc.ExecuteReader
If tname.HasRows Then
tname.Read()
tablename = tname("ControlTable")
tname.Close()
query = "SELECT * FROM TTestCase WHERE TTestCase.ElementNo = ( " _
& "SELECT ElementNo FROM [" & tablename & "])"
dc.CommandText = query
Dim rows As OleDb.OleDbDataReader
rows = dc.ExecuteReader
End If
Related
I found the following query in order to find out if a database table was created already or not:
if db_id('thedbName') is not null
--code mine :)
print 'db exists'
else
print 'nope'
Now I am wanting to use that same query within my VB.net application. This is the code I currently have elsewhere that connects to the database (that I am wanting to see if its there before doing all this):
Dim cn As SqlConnection = New SqlConnection("Data Source=DAVIDSDESKTOP;" & _
"Initial Catalog=thedbName;" & _
"Integrated Security=True;" & _
"Pooling=False")
Dim sql As String = "if db_id('thedbName') is not null " & vbCrLf & _
"Print() 'exists' " & vbCrLf & _
"else " & vbCrLf & _
"Print() 'nope'"
Dim cmd As SqlCommand = New SqlCommand(sql, cn)
cmd.Connection.Open()
Dim blah As String = cmd.ExecuteNonQuery()
cmd.Connection.Close()
Of course the issue with this is that I have to know the database name first in order to connect to the database.
I then seem to be able to connect to the master database using this:
Dim cn As SqlConnection = New SqlConnection("Data Source=DAVIDSDESKTOP;" & _
"Integrated Security=True;" & _
"Pooling=False")
Dim sql As String = "if db_id('thedbName') is not null " & vbCrLf & _
"Print() 'exists' " & vbCrLf & _
"else " & vbCrLf & _
"Print() 'nope'"
Dim cmd As SqlCommand = New SqlCommand(sql, cn)
cmd.Connection.Open()
Dim blah As String = cmd.ExecuteNonQuery()
cmd.Connection.Close()
But that query seems to throw an error on Dim blah As String = cmd.ExecuteNonQuery() of:
Additional information: Incorrect syntax near ')'.
So I'm not all sure what I am missing in order to correct the issue with the query?
Need to know how to have the query come back and say 'exists' or 'nope'
Change Print() to Print (remove the parentheses.)
Better, don't use Print at all, use select.
Dim sql As String = "if db_id('thedbName') is not null " & vbCrLf & _
"select 'exists' " & vbCrLf & _
"else " & vbCrLf & _
"select 'nope'"
Dim blah As String = CType(cmd.ExecuteScalar(), string)
ExecuteNonQuery returns the number of affected rows for updates and inserts. But what you are executing is a query.
ExecuteScalar returns the first column of the first row selected. The query above only returns one row with one value, so that's what it will return.
or do it like this
select * from sys.databases where [name] = 'thedbName'
if it returns a row, then the database exists, if not then it doesn't.
To check if a table exists within a database, use this
select * from sys.objects where [name] = 'theTableName' and type_desc = 'USER_TABLE'
I am USING THIS CODE FOr TWO Table Join and Show to DataGridView
Dim strSQL4
strSQL4 = " Select Regno, Sname,Class, Section,SUM(FeeAmount) as FeeAmount FROM FeesMaster WHERE class='" & cboClass.Text & "' GROUP By Regno,Sname,Class,Section"
strSQL5 = " Select Regno, ST_Name,Class, Section,SUM(Amount_Paid) as Amount_Paid FROM Fees_Transaction WHERE class='" & cboClass.Text & "' GROUP By Regno,ST_Name,Class,Section"
Dim DaAp4 As New SqlDataAdapter(strSQL4, con)
Dim DSet4 As New DataTable
DaAp4.Fill(DSet4)
DataGridView2.DataSource = DSet4.DefaultView
In your code above, you're not actually doing anything with strSQL5, so how do you expect it to be present on the DGV?
as#xfx suggested, you should adapt strSQL4 so that it uses the SQL from strSQL5 as a JOIN.
I just created a table programmatically. I named it as my Textbox value.
Example:
Create table " & Textbox1.text & " + ......
I want to set my table name according to my Textbox value.
Select TaskNumber,Name,Age From '" & Textbox1.text & "' "
The best pratice would be to put your textbox value in a variable:
Dim myTableName As String
myTableName = TexBox1.text
// SQL Connection
Dim conStr As String = "Server=MyServer;Database=Mydatabase;Trusted_Connection = yes"
Dim objCon As New SqlConnection(conStr)
Dim obj As SqlCommand
Dim strSQL as String
obj = objConn.CreateCommand()
// *************** Select statement *********
strSQL = "SELECT TaskNumber, Name, Age FROM " & myTableName
// **************** Create statement *********
strSQL = "CREATE TABLE " & myTableName & "(" & _
"Id int NOT NULL PRIMARY KEY IDENTITY, " & _
"ColumnTest VARCHAR(30)) "
// Execute the command
obj.CommandText = strSQL
obj.ExecuteNonQuery()
Try this:
Dim query AS String = "Select TaskNumber,Name,Age From " & Textbox1.Text.Trim().Replace("'","")
.Replace("'","") will prevent SQL-Injection attack due to the presence of single quotes in the TextBox text.
I will suggest you using RegularExpressionValidator on your TextBox to limit the allowed characters.
I am new in vb.NET and SQL. I want to view the latest input in my vb.NET program. How would I do it? Where bed number is auto-increment. Currently, this do record the changes in the database but when I want to view the details the label remains empty which it should be.
This is my code:
Dim SQLStatement As String = "SELECT name, age, date_of_confinement,type_of_sickness, " _
"type_of_IV_fluid, number_of_bottles, drop_rate " _
"FROM patient WHERE bednumber=1"
Dim cmd As MySqlCommand = New MySqlCommand
With cmd
.CommandText = SQLStatement
.CommandType = CommandType.Text
.Connection = SQLConnection
.ExecuteNonQuery()
'--read the records in database in phpmyadmin gui---
Dim myReader As MySqlDataReader = cmd.ExecuteReader
If myReader.Read Then
ViewInfo.lblName.Text = myReader.GetString(0)
ViewInfo.lblAge.Text = myReader.GetString(1)
ViewInfo.lblDate.Text = myReader.GetString(2)
ViewInfo.lblSickness.Text = myReader.GetString(3)
ViewInfo.lblFluid.Text = myReader.GetString(4)
ViewInfo.lblBottle.Text = myReader.GetString(5)
ViewInfo.lblDrop.Text = myReader.GetString(6)
myReader.Close()
End If
End With
Thanks!
Try to change the SQL statement in this way:
Dim SQLStatement As String = "SELECT TOP 1 name, age, date_of_confinement,type_of_sickness, " _
"type_of_IV_fluid, number_of_bottles, drop_rate " _
"FROM patient ORDER BY bedumber DESC"
This will sort the patient table on bednumber in descending order (so the last inserted record is on top) then get this first record (TOP 1).
Of course I suppose that bednumber is a numeric column with values autogenerated sequentially by the database in rough order of insertion.
For show the latest input, I will do this in my query
Dim SQLStatement As String = "SELECT name, age, date_of_confinement,type_of_sickness, " _
"type_of_IV_fluid, number_of_bottles, drop_rate " _
"FROM patient WHERE badnumbre=(SELECT MAX(bednumber) from patien )"
I Use The Sub query for it
I Hope it run well :)
Ran into this error message while trying to select some records off a table.
My mind is shot right now..
Any ideas? Thanks!
myreader is,
Public myReader As SqlCeDataReader
Dim currentMatch(1) As String
cmd.CommandText = "SELECT schoolid,opponent " & _
"FROM TEAM_SCHEDULE WHERE seasonid = " & i & _
" AND gameid = " & 1 & " ORDER BY id"
myReader = cmd.ExecuteReader()
Do While myReader.Read()
currentMatch(0) = myReader.GetString(0)
currentMatch(1) = myReader.GetString(1)
Loop
Educated guess:
schoolid is defined as INT, but for some reason you are using GetString instead of GetInt32 to fetch it.
Do While myReader.Read()
currentMatch(0) = myReader.GetInt32(0).ToString()
currentMatch(1) = myReader.GetString(1)
Loop
why don't use datatable?
Public myReader As SqlCeDataReader
Dim currentMatch(1) As String
cmd.CommandText = "SELECT schoolid,opponent " & _
"FROM TEAM_SCHEDULE WHERE seasonid = " & i & _
" AND gameid = " & 1 & " ORDER BY id"
Dim dt as new DataTable
dt.load(cmd.ExecuteReader())
If you want, you can query result datatable with linq
dim QueryResults = from p as datarow in dt.rows where p.seasonid<10 select p
or select a list
dim MyObjList = (from p as datarow in dt.rows select seasonid = p.seasonid, gameid = p.gameid).ToList