Query one for column headers, query 2 for row data - asp.net

I would like to know how to use asp.net vb to create a gridview that has one query be the column headers then use those column headers to populate the table. I have accomplished this in asp classic but would like to know how to to it in .net. The following are my queries that accomplish this in asp classic.
Select DOA,GroupName From Groups Where Doa is not null Order by zDOA
I use that query to populate the top of my table, then use this to get the users and their groups.
SELECT DISTINCT TM.PersonID, GroupMembers.FullNm, TM.zUpdatedOn, Location.LocationName FROM GroupMembers INNER JOIN TM ON GroupMembers.PersonID = TM.PersonID Inner JOin Location ON Location.LocationID = GroupMembers.LocationID INNER JOIN Groups ON GroupMembers.GroupsID= Groups.ID WHERE (GroupMembers.zIsActive = 1) AND GroupMembers.LocationID = "&LocationID&" AND Groups.DOA IS NOT NULL order by FullNm
That query gets people's name, their location(from StringQuery) and then finds out which groups they are in. When it cycles through which groups they are in, it compares their groups to all of the groups. When they match I put a check box in the correct spot. I have attached a image of this. The RED is from the first Query and the BLUE is from the second query. My question is how to replicate this in .net. I am unable to put the first query as the columns and fill in the rest with the second query.
![Example]

The answer is to use the sql pivot function. http://www.codeproject.com/Tips/500811/Simple-Way-To-Use-Pivot-In-SQL-Query

Related

sqlite view only produces one result when it should produce many

I have a table squitters which is full of aircraft transmissions. My view called active, returns a list of unique identifiers (hex_ident) and puts them in column d_active_hex. From this view I want to join it with my table and return the most recent transmission that contains lat,lon,alt data for each active hex_ident. My active view is working properly, but my second view is only returning one entry when I know there should be multiple, up to and including but not necessarily the number of active hex_idents. Here's the request.
cur.execute("""
CREATE VIEW IF NOT EXISTS activepos AS
SELECT hex_ident,max(parsed_time),lat,lon,altitude
FROM squitters JOIN active
ON squitters.hex_ident = active.d_hex_ident AND transmission_type = 3;
""")
I'm currently adding the results of my view called active to a list in python and then looping through the list and making a separate request for each list item like this
SELECT hex_ident,max(parsed_time),lat,lon,altitude
FROM squitters
WHERE hex_ident = ? AND transmission_type = 3
which produces the expected result but that seems inefficient and I'd rather simplify my code and learn how to do it in sql at the same time. Messing around with it, it seems like the max(parsed_time) is the issue because it's selecting the latest transmission out of every transmission, not the latest for each hex_ident but not sure how to achieve what I want.
Any ideas?
I suspect that you want to group by hex_ident:
CREATE VIEW IF NOT EXISTS activepos AS
SELECT s.hex_ident, MAX(parsed_time) parsed_time, lat, lon, altitude
FROM squitters s JOIN active a
ON s.hex_ident = a.d_hex_ident
WHERE transmission_type = 3
GROUP BY s.hex_ident
Also you should qualify all the column names with the table name/alias that contain them. In my code I left unqualified all the columns that I couldn't identify the table's alias.

Multiple inserts using 'User Defined Table Type' (asp.net sql-server)

In my ASP.NET web app I have a DataTable filled with data to insert into tblChildren.
The DataTable is passed to a stored procedure.
In the SP I need to read each row (e.i Loop through the DataTable), change a couple of columns in it (with accordance to the relevant data in tblParents) and only then insert the row into tblChildren.
SqlBulkCopy wouldn't do and I don't think TVP will do either (not sure... not too familiar with it yet).
Of course I can iterate through the DataTable rows in the app and send each one separately to the SP, but that would mean hundreds of round trips to the SqlServer.
I came across two possibilities that might achieve that : (1) Temp table
(2) Cursor.
The first is quite messy and the second, as I understand it, is NOT recommended)
Any guidance would be much appreciated.
EDIT :
I tried the approach of user-defined Table Type.
That works because I populate the Table Type (TT_Children) with values in the TT_Child_Family_Id column.
In real life, though, I will not know these values and I would need to loop thru #my_TT_Children and for each row get the value from tblFamilies, something like this :
SELECT Family_Id FROM tblFamilies WHERE Family_Name = TT_Child_Last_Name
(assuming there is always an equivalent for TT_Child_Last_Name in tblFamilies.Family_Name)
So my question is - how to loop through the table-type and for each row look up a value in a different table?
EDIT 2 (the solution) :
As in Amir's perfect answer, the stored procedure should look like this :
ALTER PROCEDURE [dbo].[usp_Z_Insert_Children]
#my_TT_Children TT_Children READONLY
AS
BEGIN
INSERT INTO tblChildren(Child_FirstName,
Child_LastName,
Child_Family_ID)
SELECT Cld.tt_child_FirstName,
Cld.tt_child_LastNAme,
Fml.Family_Id FROM #my_TT_Children Cld
INNER JOIN tblFamilies fml
ON Cld.TT_Child_LastName = Fml.Family_Name
END
Notes by Amir : column Family_Name in tblFamily must be unique and preferably indexed.
(Also I noticed that in case TT_Child_LastName does not have a match in tblFamilies, the row will not be inserted and I'll never know about it. That means that I have to check somehow if all rows were successfully processed).
You can join tblFamilies into the insert in the procedure and take the value from there. Much more efficient than looping through.
Or create a cursor and do one child at a time.
1) Make sure there is only one occurance of FamilyName in tblFamilies.
2) Make sure that if tblFamilies is a large table, then the FamilyName column is indexed.
INSERT INTO tblChildren(Child_FirstName, Child_LastName, Child_Family_ID)
SELECT Cld.tt_child_FirstName,
Cld.tt_child_LastNAme,
Fml.FamilyID
FROM #my_TT_Children Cld
INNER JOIN tblFamilies fml on Cld.TT_Child_LastName = Fml.FamilyName
But be aware that if tblFamilies has more than one entry per Family_Name, then this will duplicate the data. In this case you will need to add more restrictions in the where.

New to sqlite and database work, how do I do this query?

I have a project I am working on and I am wanting to create a query that involves two tables from my database as pictured below.
What I want from the query is if DMN_LIST_COLS on the DOMAIN data table equals 1 I want to retrieve all the values from DMV_VALUE_1 of the DOMAIN_VALUE data table. What is the correct format for this query?
I know the query below is incorrect but how do I change this?
SELECT DMV_VALUE_1 FROM DOMAIN_VALUE WHERE DMN_LIST_COLS='1' FROM DOMAIN
Give this a try:
SELECT DOMAIN_VALUE.DMV_VALUE_1
FROM DOMAIN_VALUE INNER JOIN DOMAIN ON DOMAIN_VALUE.DMV_ID = DOMAIN.DMN_ID
WHERE DOMAIN.DMN_LIST_COLS ='1';
If DOMAIN.DMN_LIST_COLS contains actual numbers instead of text, you will want to remove the single quotes surrounding the 1 in the WHERE statement.

Comparing records of two tables and discarding matches

I am trying to implement an idea where I have two sql tables in a database.
Table Info which has a field Nationality and the other Table Exclusion which has a field Keyword.
`Info.Nationality` `Exclusion.Keyword`
|British| |France|
|resteraunt de France| |Spanish|
|German|
|Flag Italian|
|Spanish rice|
|Italian pasta
|Irish beef|
In my web application I am creating a GridView4 and through a DataTable and SqlDataAdapter I am populating that GridView4 with the SQL command:
SELECT DISTINCT Info.Nationality WHERE Exclusion.Keyword NOT LIKE '%Spanish%'
That SQL statement retrieves all the distinct records in Info.Nationality which do not contain the word spanish.
What I am currently doing is that in the web app which is in vb.net I am adding two different GridViews, each have the data of each table which means that GridView2 has DISTINCT Info.Nationality and GridView3 has Exclusion.Keyword and then adding another GridView4 to display the results of the above SQL command.
The idea is to retrieve all the distinct records from Info.Nationlity which are not suppressed by the keyword constraints in Exclusion.keyword. So from the above mentioned Sql command the GridView4 will retrieve all the records which do not have the word "Spanish".
I am doing all of this in a nested for loop where in the first loop it takes each record (one by one) from Info.Nationality e.g.for each row As DataRow in Me.GridView2.Rows() and compare it with the second for loop which goes till the end of the Exclusion.Keyword which would be like For i=0 To Gridview3 - 1.
The problem is that in that sql statement I have to explicitly specify the word to compare. I tried adding the records of Exclusion.Keyword in a String and then replacing the Spanish Keyword In between the NOT LIKE with the name of the String which is Keywords and then assigning the name a parameter with cmd.parameter.addwithvalue(#String, Keywords). However this is not working, it is only comparing with the last record in the string and ignoring the first.
The idea behind all of this is to display all the records of Info.Nationality in GridView4 which do not contain the keywords in Exclusion.Keyword.
Is there an easier or more effecient way to do this? I was thinking of an Inner Join with a Like command but that is not my problem. My problem is that how can I compare each record one by one of Info.Nationlity with all the records in Exclusion.keyword and then retrieving the ones that do not match and discarding the ones that match.
Then in Gridview4 how can I edit the records without reflecting those changes or affecting in Info.Nationality but rather only Inserting to Exclusion.Keyword the changes.
SOLVED by adding ToString() after Text
In my asp.net web app, I tried this, but didn't work: (SOLVED)
`SELECT DISTINCT Nationality
FROM Info Where NOT EXISTS(SELECT * FROM Exclusion WHERE Info.Nationality LIKE '%' + #GridView +'%')`
`cmd.parameters.AddwithValue("#GridView", GridView3.Rows(i).Cells(0).Text.ToString())`
GridView3 Here has the Exclusion.Keywords data.
Would really appreciate your suggestions and thoughts around this.
You do not need to do this one-by-one, or "Row by agonizing row" as some DBAs are fond of describing this type of approach. There are lots of ways to write a query to only return the records from Info.nationality that do not match the exclusion keywords as a single expression.
My preference is to use the EXISTS clause and a correlated subquery:
SELECT Nationality
FROM Info I
WHERE NOT EXISTS(SELECT * FROM Exclusion WHERE I.Nationality LIKE '%' + Keyword + '%')
You can also express this as a left join.
SELECT I.Nationality
FROM Info I
LEFT OUTER JOIN Exclusion E
ON I.Nationality LIKE '%' + E.Keyword + '%'
WHERE E.Keyword IS NULL
The left join will return all the rows from info and insert nulls in the columns for Exclusion except where the join criteria matches. By filtering for only where those values are null, you can avoid the matches.

Complex datasource issue in Dynamics AX

I have a grid that displays lines from a table. Now, I have these two requirements:
Show only the lines that contains values in the "hour" fields. The "hour" field is an array type.
Show the lines from a project and its subproject
My problem is this: to meet requirement #1, I need to use a select statement in my datasource since I cannot access array value using QueryBuildDataSource (this is a known limitation in Dynamics AX).
But to meet requirements #2 I need to have two "exists join", and this is not possible in Dynamics AX. For example the following code would not work:
select from table where
exists join tableChild where projectId = MyProjectId OR
exists join tableChild where parentProjectId = MyProjectId
How would someone address this issue?
From the select statement example you provided, it appears it may not be necessary to have two exist joins. A single exists join with the "OR" for the two possible conditions in its where clauses may be sufficient, of course, you should still have some relationship between table and tableChild for the join to make logical sense.
select from table
exists join tableChild
where (tableChild.projectId = MyProjectId || tableChild.parentProjectId = MyProjectId)
You can use array values in query ranges providing field IDs using fieldID2Ext function.
You can build view and apply confitions on top of it.

Resources