I'm trying to show columns in a query where the value is not null in Ms Access (2010).
I have a query that now gives me this, where name, field1,... are the column headers:
Name | field1 | field2 | field 3 | field 4 | field5
mike | x | | x | x |
So now I don't want to see Field2 and Field5 in that query. I have a lot more fields then 5, and I only want to see the one with a value.
It's also fine If you can tell me a way to get the column names ( ex field1, field3,field4)
Thanks
You'll have to use a simple WHERE statement in your SQL. For example:
SELECT tbl.*, tbl.field2, tbl.field5
FROM tbl
WHERE tbl.field2 Is Not NULL AND tbl.field5 Is Not Null;
This will return all fields and all rows, where field2 and field5 are not Null.
EDIT: Since I am more familiar with vba, I would use the following approach to reach the desired output as stated in the comments.
Start by creating the query.
SELECT tbl.*
FROM tbl
WHERE tbl.ID = 12345;
Let's say you name it "qry_record". Afterwards, I would loop through the fields with a recorset, and create a new dynamic sql statement with the fields that have a value.
Dim rs As Recordset
Dim fld As Field
Dim sqlstatement As String: sqlstatement = "SELECT "
Set rs = CurrentDb.OpenRecordset("qry_record")
With rs
.MoveFirst
For Each fld In .Fields
If IsNull(fld.value) = False Then
Debug.Print fld.Name
sqlstatement = sqlstatement & "tbl." & fld.Name & ", "
End If
Next
End With
rs.Close
Set rs = Nothing
sqlstatement = sqlstatement & "FROM tbl"
DoCmd.RunSQL sqlstatement
EDIT: I have tested the code, and made a minor adjustment. Should work fine now on any table in your access database.
Related
I want access give me the the first value from the selected table and column.
But access are given to me random value from the selected table and column.
Question
Have someway to access give to me like this example:
My table is "tblExample" and have 2 columns the header of each is [Column1] and [Column2] inside each header contains this values
+---------+----------+
| Column1 | Column2 |
+---------+----------+
| 5 | mark |
| 3 | stewie |
| 2 | stack |
| 16 | overflow |
+---------+----------+
I want read the first value in loop of the [Column1] from the table "tblExample" and bring to me in sequence.
example value = 5/ after 3 / 2 / 16 ...
But my code is showning this values random like 16/5/3/2
This is my code
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim VarA As String, varFR, varLR
Set db = CurrentDb
Set rs = db.OpenRecordset("tblExample")
If rs.EOF Then
FindRecordCount = 0
Else
rs.MoveLast
FindRecordCount = rs.RecordCount
End If
varLR = FindRecordCount
Dim i As Long
For i = 0 To rs.Fields.Count - 1
rs.MoveFirst
varFR = 1
Do While varFR < varLR
If IsNull(rs.Fields(i).Value) = True Then
GoTo pula1
End If
VarA = rs.Fields(i).Value
Debug.Print VarA
pula1:
rs.MoveNext
varFR = varFR + 1
Loop
Next
Tables without primary key don't have an inbuilt sort order. So the result of a recordset loop can be random.
You can either provide the sort order when opening the recordset
Set rs = db.OpenRecordset("SELECT * FROM tblExample ORDER BY Column1")
(but the result can still be random if Column1 contains duplicate values!)
or if you want the order, in which the records were inserted, add a AutoNumber primary key column to your table.
For readability you should still specify the order -
Set rs = db.OpenRecordset("SELECT * FROM tblExample ORDER BY ID")
you can loop trough like this, after you set the Recordset:
rs.MoveFirst
Do Until rs.EOF
--- Stuff happens
rs.MoveNext
Loop
So its looping through the records like they are in the table. If you want another sequence you can sort the recordset before:
Set rs = db.OpenRecordset("SELECT * FROM tblExample ORDER BY Column1 ASC")
I have VBA code that queries a table. The Query view in MS Access returns the correct results, however the vba returns a different result.
Table called tbl_ADMIN_CLASS_INFO
Client_ID | POLICY_GROUP
12345a | 1
12345a | 2
12345a | 2
12345a | 2
12345a | 2
Column Definitions from Table:
CLIENT_ID = Text
POLICY_GROUP = Number
VBA
Public Sub NextPageControl()
Dim dbs As Database
Dim rst As Recordset
Dim CurrentTableName As String
Dim CurrentFormName As String
Dim NextPageSQL As String
Dim CurrentPage As Form
Dim LastRecord As Integer
Dim Nextpage As Integer
Dim TestPolicy As Long
Dim TestClient As String
TestPolicy = Forms!frm_ADMIN_CLASS_INFO.POLICY_GROUP 'Stepping Through Code shows 12345a
TestClient = Forms!frm_ADMIN_CLASS_INFO.CLIENT_ID 'Stepping Through Code shows 2
CurrentTableName = Screen.ActiveForm.RecordSource
CurrentFormName = Screen.ActiveForm.Name
Set CurrentPage = Screen.ActiveForm
Set dbs = CurrentDb
NextPageSQL = "SELECT * FROM " & CurrentTableName & " WHERE ((POLICY_GROUP = " & TestPolicy & ") AND (CLIENT_ID = '" & TestClient & "'))"
Debug.Print NextPageSQL
Set rst = CurrentDb.OpenRecordset(NextPageSQL, dbOpenDynaset)
MsgBox rst.RecordCount
...More Stuff
The problem is that this VBA returns 5 for rst.RecordCount when it should return 4....
Firstly, the following instruction is not optimal as it can fool you if you're in the case where your form's record source is a SQL query and not a table:
CurrentTableName = Screen.ActiveForm.RecordSource
So make sure that this instruction retruns the correct table name.
Secondly: using recordset.recordcount might not return the expected results depending on your cursor type and the datasource. From microsoft:
The cursor type of the Recordset object affects whether the number of
records can be determined. The RecordCount property will return -1 for
a forward-only cursor; the actual count for a static or keyset cursor;
and either -1 or the actual count for a dynamic cursor, depending on
the data source.
So to be sure you're always returning the correct amount of records, do a :
rst.movelast
prior to do the recordcount
Your code should work fine after those corrections.
I'm learning SQL Server and VB.NET. My problem is how to select and make a condition to specific row in the table.
Like, that I have table with two columns name, age, and I want to select rows where name is "XY".
After that, make a condition with an (if) statement like: if age (in the table) larger than 20.
Do some thing or each one his name "xy" print his age in a messagebox.
You can try this in one query like this:
select * from yourtable where name = 'XY' and age > 20
Noor, Rahul was exactly correct in what was recommended. It sounds like you have little experience with how to get data from a SQL query into a useable form so you can test and manipulate or analyze data. For technology, look at ADO, and ADOX usage in VB.NET with SQL queries. My recommendation is for you to purchase one or more good books on VB.NET, so you can fully understand how to move forward.
Dim filename As String = "C:\myfile.mdb"
Dim tablename as String = "mytable"
Dim ConnString As String = "Provider=Microsoft.Jet.OLEDB.4.0; Data source =" & filename
Dim cn As New OleDbConnection(ConnString)
cn.Open()
Dim qry As String
Dim cmd As New OleDbCommand(qry, cn)
qry = "SELECT * FROM [" & tablename & "] WHERE name = "XY" and age > 20 ORDER by age "
cmd.CommandText = qry
cmd.Connection = cn
Dim drdata As OleDbDataReader = cmd.ExecuteReader
Dim Cnt As Integer = 0
Dim name(), age() as Object
Do While drdata.Read
Cnt += 1
Redim Preserve name(Cnt)
Redim Preserve age(Cnt)
name(Cnt) = drdata.Item("name")
age(Cnt) = drdata.Item("age")
Loop
drdata.Close()
For i As Integer = 1 to Cnt
If age(i) = 20 Then
' do anything you want here
End If
Next i
I have an access table with the fields
ID
Field1
Field2
Field3
I also have a word table with headers
ID | Field1 | Field2 | Field3
How can I import automatically all the data from the table into an assess database from the word file ?
Importing automatically doesnt sound easy, but you could do it programmatically.
From Access, you'd do something like this:
dim base as string: base = "INSERT INTO tblname (ID, Field1, Field2, Field3) VALUES ("
dim sql as string
dim ii as long
dim jj as long
dim wrd as object
dim wrdDoc as object
'
docmd.setwarnings false
set wrd = createObject("Word.Application")
wrd.visible = false
set wrdDoc = wrd.Documents.Add("name of word document containing table")
with wrdDoc.Tables(1) 'assuming first table in document
for ii = ? to .Rows.Count 'if the table has column headings, ? = 2, else 1
sql = base
for jj = 1 to 4 '4 = count of columns
sql = sql & iif(jj = 1, "", ",") & CStr(.Cell(ii, jj))
next jj
sql = sql & ")"
docmd.runsql sql
next ii
end with
docmd.setwarnings true
wrd.Quit
set wrddoc = nothing
set wrd = nothing
How can i compare two MS ACCESS 2007 databases.Both databases contain same tables with same feilds ad structure.i need to compare the record values between two databases to detect any difference in record values.
ACCESS 2007 Database1
serial no. | NAME | ADDRESS
1 smith street 1
2 john street 4
3 alix street 8
ACCESS 2007 Database2
serial no.| NAME | ADDRESS
1 smith street 1
2 jhn stret 4
3 alix street 8
I need a VBA code for ms access that can detect the differece of records,just as the records at serial number two.
First thing you should do is link in one of the tables to the other database, e.g link the Database 2 table into database one (this allows both to be queried together) then you could use this simple example with concatenation to determine if all the fields strung together match based on the serial number:
SELECT T1.*, T2.*
FROM Table1 As T1, Table2 As T2
WHERE T2.[serial no.] = T1.[serial no.]
AND T2.[NAME] & T2.[ADDRESS] <> T1.[NAME] & T1.[ADDRESS]
You could also specify the columns with each of their own condition if you prefer.
NOTE: This is assuming you are only looking for differences where the serial no matches, if you also need to identify records that may appear in one table but not the other then you will need to use an "Un-matched" query, the query designer can help you with this or post back and I can update my answer.
Option Compare Database
Private Sub Command4_Click()
Dim tablename1, tablename2 As String
tablename1 = Text0.Value
tablename2 = Text2.Value
'On Error GoTo Err_cmdValidateGeneralInfo_Click
Dim F As DAO.Field
Dim rs As DAO.Recordset
Dim rs1 As DAO.Recordset
Set curDB = CurrentDb()
'If Me.DateModified = Date Then
'Adds new employees to the TT_GeneralInfo table in the FTEI_PhoneBook.mdb - which is used thru out the AP databases.
' DoCmd.OpenQuery "qryEmpData_TT_General"
strsql = "Select * from " & tablename1
Set rs = curDB.OpenRecordset(strsql)
strsql1 = "Select * from " & tablename2
DoCmd.CopyObject , "Unmatched_records", acTable, tablename1
curDB.Execute "DELETE FROM Unmatched_records"
Set rs1 = curDB.OpenRecordset(strsql1)
Do Until rs.EOF
For Each F In rs.Fields
If rs.Fields(F.Name) <> rs1.Fields(F.Name) Then
'rs.Edit
strsql = "Select * into test from " & tablename1 & " where " & F.Name & " = """ & rs.Fields(F.Name) & """"
DoCmd.RunSQL strsql
If DCount(F.Name, "test") <> 0 Then
GoTo append_unmatch
'appending unmacthed records
append_unmatch:
strsql2 = "insert into Unmatched_records Select * from test"
DoCmd.RunSQL strsql2
'if record doesnt match move to next one
GoTo Nextrecord
End If
' rs.Fields(F.Name) = rs1.Fields(F.Name)
' rs.Update
End If
Next F
Nextrecord:
rs.MoveNext
rs1.MoveNext
Loop
'To check whether tables matched or not
Dim rs2 As DAO.Recordset
strsql3 = "select * from Unmatched_records"
Set rs2 = curDB.OpenRecordset(strsql3)
For Each F In rs2.Fields
If DCount(F.Name, "Unmatched_records") <> 0 Then
MsgBox ("The two tables didnt match. Check table test for unmatching reocrds.")
Else
MsgBox ("Tables match!")
End If
Exit Sub
Next F
rs2.Close
End Sub