How to show results by Category in SQL and display in classic ASP - sql

I have a table from where I want to display records on the page grouped by categories in Classic ASP in such order that the Latest records are displayed on top. I am using MS SQL 2005 server.
For example table is like
ID Data1 Data2 Category
1 abc def test1
2 rrr 344 test2
3 ttt edf test1
4 www ghj test2
sql="select * from TABLE where Category='test1" and Category='test2' order by ID desc"
I want to display the all the data from category Test1 and Test2 on the page at different places. How to separate results by category?
Thanks,

If you want to display the results in different places, just run both SQL statements and store the results into 2 different Recordsets.
<%
set rs1=Server.CreateObject("ADODB.recordset")
set rs2=Server.CreateObject("ADODB.recordset")
SQL1="select * from TABLE where Category='test1' order by ID desc"
SQL2="select * from TABLE where Category='test2' order by ID desc"
rs1.Open SQL1, ConnectionString
rs2.Open SQL2, ConnectionString
Test1_ID = rs1("ID")
Test1_Data1 = rs1("Data1)
Test1_Data2 = rs1("Data2")
Test1_Category = rs1("Category")
Test2_ID = rs2("ID")
Test2_Data1 = rs2("Data1")
Test2_Data2 = rs2("Data2")
Test2_Category = rs2("Category")
%>
This code assumes you already have set your connection string = ConnectionString and have already opened it, and side note, you can share the connection, or you can make one for each recordset, if its not that much data it won't matter, but if its a larger chunk of data, it wouldn't hurt to have 2 connection objects.
Now when you go to display the results you can just rs1.MoveNext to move to the next record in the first set, and rs2.MoveNext to move to the next record in the second recordset. Your question was how to be able to display the records in different places, so now you have the variables names and a way to move to the next record, if you know how to move through a loop advancing the recordsets until you reach the last record, you just do that for both recordsets, and as each one is being done and displayed, they will be separate until you write the part to display the results from rs2 as well.
Closing Notes - In case you need to be specific in your SQL, you can specify the source in the format of database.tablename. So in the example you would do something like this for SQL1:
select * from DATABASE.TABLE where Category='test1' order by ID desc

Related

SQL query to display rows of 2 different tables

I'm trying to figure out how to pull all rows from two different tables with the OutageID = X. The purpose of this is to view the current outage and all the revisions in one statement to see all of the changes. Below is an example I was trying. However, it puts it all in one row. I want it to display all rows separately like you would if you were to query SELECT * From Table WHERE X = Y.
The Current Outages are in one table and the history is in another so they are not written over and not to change the design of the current DB.
Outages Table
`strSQL = "SELECT Outages.OutageID, Outages.Outage, Outages.Building,
Outages.OutageType, Outages.OutageStart, Outages.OutageStartTime,
Outages.OutageEnd, Outages.OutageEndTime, Outages.Duration,
Outages.Reason, Outages.Areas, Outages.Comment, Outages.ORN,
Outages.Contact, Outages.Phone, Outages.Job, Outages.Timestamp
FROM Outages
WHERE (((Outages.OutageID)=3305));"`
Outage History Table
`strSQL = "SELECT OutageHistory.RevisonID, OutageHistory.OutageID,
OutageHistory.Outage, OutageHistory.Building,
OutageHistory.OutageType,
OutageHistory.OutageStart, OutageHistory.OutageStartTime,
OutageHistory.OutageEnd, OutageHistory.OutageEndTime,
OutageHistory.Duration, OutageHistory.Reason, OutageHistory.Areas,
OutageHistory.Comment, OutageHistory.ORN, OutageHistory.Contact,
OutageHistory.Phone, OutageHistory.Job, OutageHistory.Timestamp
FROM OutageHistory
WHERE (((OutageHistory.OutageID)=3305));"`
`Private Sub All_Revision_Histoy_Click()
Dim strSQL As String
strSQL = "SELECT * From OutageHistory WHERE OutageHistory.OutageID = " &
Me.OutageID & ";"
Debug.Print strSQL
ShowDataSheet strSQL`
I think that I might need to create a temp table and insert both rows for the results and then Delete the table when its closed. However, I am not sure how to do that. I already feel I may of bitten off more than I can chew with this one. Thank you in advance.
select * from (
select 1 as revisionID, Outages.* FROM Outages
WHERE (((Outages.OutageID)=3305))
union
select OutageHistory.* FROM OutageHistory
WHERE (((OutageHistory.OutageID)=3305))
) order by revisionID desc

Find changes made in PGSQL table using SQL in Excel VBA

Is it possible to create an SQL query to compare a field within a single table to see if a change has been made and if possible list the before and after?
I have the following SQL query written in Excel 2010 VBA, which connects to an Oracle PostGreSQL database
Dim au As String
au = "SELECT id, priority, flag, code " _
& "FROM hist WHERE ( aud_dt >= '18/05/2020' AND aud_dt <='18/05/2020' ) " _
Set rs = conn.Execute(au)
With ActiveSheet.QueryTables.Add(Connection:=rs, Destination:=Range("A1"))
.Refresh
End With
Where fields include:
"priority" is the field that I'd like to check for changes which will
be a single number between 0-9
"code" is the record that has been
assigned the priority and is a mixture of numbers and letters up to 7
characters
"flag" shows a 1 as the active record, and 2 as an edited
record
"id" refers to the user account
I'd ideally like to end up with something like: id | priority | flag | priority_old | flag_old | code
Which should show the before and after changes to the priority. If the record shows priority=3 and flag=2 and code=Ab12, there must also be record with a 1 flag, as that is now the active record. If it has the same priority number for the code I'm not interested in it as that just means something else was changed instead as I have not listed all the column fields.
If the active record now shows priority=4, flag=1 and code=Ab12, that would be exactly the record I need to see.
Consider a self-join query (possibly you need to adjust date filter in WHERE depending on when items change):
SELECT h1.id, h1.priority, h1.flag,
h2.priority AS priority_old, h2.flag AS flag_old, h1.code
FROM hist h1
LEFT JOIN hist h2
ON h1.code = h2.code
AND h1.priority <> h2.priority
AND h1.flag = 1
AND h2.flag <> 1
WHERE (aud_dt >= '2020-05-18' AND aud_dt <='2020-05-18')

update main table from two others with modification of data before updating

I have two tables that I need to update. I have to go through every record on one table then do some modifications to the data then upload the modified
data to another table!
The two tables have 3,000 records and 11,000 records. Plus I also have to
check some info from a third table with about 50 records!
Dim id
Dim fly_SQL
id="user1"
Dim rsc1_conn As ADODB.Connection
Set rsc1_conn = CreateObject("ADODB.Connection")
rsc1_conn.Provider = "SQLOLEDB"
rsc1_conn.ConnectionString = "SERVER=companyserver;UID=" & id &
";Trusted_Connection=Yes;DATABASE=DATAbank" '
rsc1_conn.Open
Set rsc1 = CurrentDb.OpenRecordset("SELECT * FROM main_database",
dbOpenDynaset, dbSeeChanges)
rsc1.movefirst
do until rsc1.EOF
fly_SQL = "Select * from alt_db where alt_db.number = main.net_number"
Set rsc2 = CurrentDb.OpenRecordset(fly_SQL)
do stuff
code = dlookup( "type_def", "third_rec" , alt_db.activity = activity)
The two tables both use net_number as a reference which on the main is primary key unique, but the alt_db has multiple entries.
So basically I have to loop through each net_number on the main, look at the matching net_number on the alt_db then compare an activity field
with a third table to see which field I update on the main! If it's a Project management expense I put it in the main.PM_cost. The net_number in alt_db might repeat for 10 other expenses that need to be funneled into their proper expense categories in the main DB! As an example:
Main table looks like
net_number
first record shows
main.netnumber = 123456
main.cont_cost
main.PM_cost
main.mgmt_cost
alt_db table looks like
alt_db.net_number
alt_db.activity
alt_db.PM_cost
alt_db.const_cost
alt_db.mgmt_cost
third_rec looks like
third_rec.code
third_type
where data can be something like con1 , sabb ,
code type
sauf construction
con1 management
I130 project management
And needed rules:
check alt_db.activity with third_rec.act and return activity type
If activity type is construction then I put the alt_db.cost into main.const_cost
If activity type is project_mgmt then I put the alt_db.cost into main.PM_cost. The alt_db.activity could be con1 or SAF4 and the type is determined by the third_rec table.
Trying to figure out the best (most efficient way) to go about this.
Any suggestions?
The above code will surely be missing proper variable definitions and such but it's just for explaining my dilemma!
I could probably do it with DLookup but I don't think that would be very efficient!
Pete
Best way was to build a query that produces a file filtered data from the Main and alt_db to group the activities by net_number . Then use a case to determine which fields from alt_db to update using the third file and update the result in the proper fields on the main db.

How do I get a field of a datatable when I know column name and a row ID, without looping?

How do I get a field of a datatable when I know column name and a row ID, without looping?
For instance; I want the “Total Sold” value when Region = City and Product = Legos. This is something I have struggled with for a long time, probably because I think in SQL so looping through everything all the time doesn’t always seem like the correct way to go. BUT if I just need to learn to think like a VB developer and always loop to get something out of a list or table, please let me know.
I have a series of asserts comparing two datatables, one that has one row with a named column for each cell (from XML produced by SSRS), and another datatable that has one row for each unique value in a region (produced from a SQL query).
Table from SQL (mockup dataset):
Region Prod Total Sold
City Legos 68
State Legos 90
Nat. Legos 200
City ToyB 20
State ToyB 30
Nat. ToyB 40
City ToyC 450
State ToyC 600
Nat. ToyC 900
Table from XML (dataset returned from SSRS):
City_Legos State_Legos Nat_Legos City_ToyB State_ToyB Nat_ToyB City_ToyC State_ToyC
68 90 200 20 30 40 450 600
The part of the assert statement that gets data from the XML based datatable is easy, because there is only one row (index 0), and I can just name the column I want:
Dim xmlRow As DataRow = xmlDatatable.Rows(0)
Assert.AreEqual(“my SQL cell goes here”, xmlRow.Field(Of Integer)(“City_Legos”))
And I can do one assert for each of the specified columns. Many of the columns won’t be tested, and they have specific names, so I can’t simply loop through the columns. So what do I put in “my SQL cell goes here” to return the Total Sold for City and Legos? Obviously in SQL it would be easy: SELECT TOP 1 Total_Sold WHERE Region = City and Prod = Legos.
I am currently looping through the SQL datatable and testing each cell for my criteria, but that logic gets huge because I have to wrap each like in If…Then, like this:
For Each m As DataRow In mySqlTable.Rows
If m.Field(Of String)("Prod") = "Legos" Then
If m.Field(Of String)("Region") = "City" Then
Assert.AreEqual(m.Field(Of Integer)("TotalSold"), xmlRow.Field(Of Integer)(“City_Legos”))
End If
If m.Field(Of String)("Region") = "State" Then
Assert.AreEqual(m.Field(Of Integer)("TotalSold"), xmlRow.Field(Of Integer)(“State_Legos”))
End If
If m.Field(Of String)("Region") = "Nat" Then
Assert.AreEqual(m.Field(Of Integer)("TotalSold"), xmlRow.Field(Of Integer)(“Nat_Legos”))
End If
End If
Next
I’m hoping I can do something like a select or LINQ or Function?
Something like this would be nice:
Dim result as Integer = mySqlTable.Select.First(“Region = City and Prod = Legos“)
Or:
Assert.AreEqual(mySqlTable.Select.First(“Region = City and Prod = Legos“), xmlRow.Field(Of Integer)(“City_Legos”))
This is a unit test, so I will always know the column and field names returned by SSRS.
Getting the cell by Column name and row identifier has always been something I’ve struggled with, so hopefully I can finally get this solved.
Thanks!
You could use the Datatable Compute method. Replace (“my SQL cell goes here” with
CInt(mySqlTable.Compute("SUM([Total Sold])", "[Region] = 'City' and [Prod] = 'Legos'"))
This is assuming that the rows are unique and no null values.

INSERT INTO increment control field

I'm using MS-ACCESS database.
From the prject I use and made some other questions the table NOEUDS and INFRA (that should be updated):
Table INFRA:
RECNO - NOEUD - SECURISE
00000008 C002 F
00000005 C009 F
00000001 C035 F
00000002 C001 F
00000003 C036 F
00000006 C012 F
00000007 C013 F
TABLE NOEUDS:
NOEUD TYPE_MAT N_AMONT
C021 COF 100
C022 COF 229
C023 COF 130
C002 COF 111
I want to create a query that checks on NOEUDS the nodes C* that are missing inside INFRA table, if not should be inserted a new one.
The problem is the RECNO field that works as a control and can not be duplicated (not primary key because all the DB is only a repositoty for the program that controls it).
All the fields are text so RECNO is a consecutive counting using HEX numbers as shown.
I used the query to select:
SELECT (SELECT MAX(CINT(INFRA.RECNO))+1 AS N FROM INFRA),
NOEUDS.NOEUD, "F" AS Expr2
FROM NOEUDS
WHERE (((NOEUDS.NOEUD) Like "C*"
And (NOEUDS.NOEUD) Not In (SELECT NOEUD FROM INFRA)));
The result was:
9 C021 F
9 C022 F
9 C023 F
SHOULD BE:
9 C021 F
A C022 F
B C023 F
I need some help on this one so I can insert the correct RECNO in hexadecimal counting after 00000019 passes to 0000001A and so on.
thanks in advance
UPDATE 1:
The program we use uses a Access database as storage. When I add a noeud using the program I have to insert some more info using the menus needed for the maps and as built information. The problem is that a lot info is redundant and the program can not handle it automatically. I am trying to work lees and insert the possible information using querys.
Every time I insert a noeud in noeuds table, is needed to insert a line in INFRA table only with RECNO (sequential counting from the last one), the NOEUD and some other info (to complete the autocad table tag). Since I have hundreds of Cxxx, Bxxx, Pxxx, Gxxx equipments I sabe for each project some hour of boring work.
I need help on counting a sequential way of adding RECNO for each NOEUD found in NOEUDS table that will be inserted in INFRA table.
UPDATE 2:
I'm inserting each noeud by hand. Is it possible to join in a way that it takes the list from the noeuds that I want to insert and insead of doing 1 by 1 it takes the list and does in a sequence?
the 2 queries are these:
Equipes I want to add at table INFRA:
SELECT NOEUDS.NOEUD
FROM NOEUDS
WHERE (((NOEUDS.NOEUD) Like "C*" And (NOEUDS.NOEUD) Not In (SELECT NOEUD FROM INFRA)));
Insertion by hand:
INSERT INTO INFRA ( recno, NOEUD, SECURISE )
SELECT (SELECT Right(String(8, "0") & Hex(Max(Val("&H" & RECNO)) + 1), 8) AS N FROM INFRA), NOEUDS.NOEUD, "F" AS Expr2
FROM NOEUDS
WHERE (NOEUDS.NOEUD=[INSERT CHAMBRE?]);
I think a VBA solution should be better than trying to do what you want with only SQL. If you don't have much VBA experience, it could still be achievable because the required VBA should be fairly basic. See if this code outline is enough to get you started.
Public Sub AddToInfra()
Const cstrQuery As String = "qryUnmatchedNoeuds" ' Note 1 '
Dim db As DAO.Database ' Note 2 '
Dim fld As DAO.Field
Dim rsFrom As DAO.Recordset
Dim rsTo As DAO.Recordset
Set db = CurrentDb
Set rsFrom = db.OpenRecordset(cstrQuery, dbOpenSnapshot)
Set rsTo = db.OpenRecordset("infra", dbOpenTable, dbAppendOnly)
Do While Not rsFrom.EOF
rsTo.AddNew
For Each fld In rsFrom.Fields ' Note 3 '
If Not fld.Name = "RECNO" Then
rsTo.Fields(fld.Name).Value = fld.Value
End If
Next fld
rsTo!RECNO = Next_InfraRecno ' Note 4 '
rsTo!SECURISE = "F" ' Note 5 '
rsTo.Update
rsFrom.MoveNext
Loop
rsTo.Close
rsFrom.Close
Set fld = Nothing
Set rsFrom = Nothing
Set rsTo = Nothing
Set db = Nothing
End Sub
Notes:
I used a saved query based on my best guess as to what you want. See the SQL below.
DAO.Database requires a reference to Microsoft DAO Object Library. If your Access version is 2000 or maybe Access XP, you may need to set that reference (from VBE main menu, Tools->References).
I decided the destination table would include fields which match the name and data type of the fields in the source recordset. If that doesn't work for you, substitute something like this for each of the common fields: rsTo!YourFieldNameHere.Value = rsTo!YourFieldNameHere.Value (And drop .Value if you prefer.)
Create a Next_InfraRecno() function to return the next RECNO value. Translate the approach we used earlier into a function. Post a new question if you run into trouble ... show us your code, error message and line which triggers the error (if any), and anything else we need to know. :-)
I got the impression you want SECURISE = "F" for each of the inserted rows.
In a comment you mentioned "Use field ANCIEN for storage of counting". I don't know what's involved for that and hope, whatever it is, you can integrate it into this code outline. If not, sorry. :-(
Here is the SQL for my qryUnmatchedNoeuds query:
SELECT n.DELETED, n.NOEUD
FROM
noeuds AS n
LEFT JOIN infra AS i
ON n.NOEUD = i.NOEUD
WHERE
(((n.NOEUD) Like "c*")
AND ((i.NOEUD) Is Null));
Although I don't understand your question very well, I hope this answer provides something you can use.
My INFRA table has a text column named RECNO. The table contains one row.
RECNO
00000019
This query give me "1A" as N.
SELECT Hex(Max(Val("&H" & RECNO)) + 1) AS N
FROM INFRA;
To pad N with zeros to a width of 8, I can use this query which gives me "0000001A" as N.
SELECT Right(String(8, "0") & Hex(Max(Val("&H" & RECNO)) + 1), 8) AS N
FROM INFRA;
Regarding the rest of your question, my instinct would be to open a recordset containing the unmatched NOEUDS.NOEUD values, then move through the recordset rows and insert each NOEUD value, your custom RECNO sequence number, and the "other info" into the INFRA table.