Run time Exception with SQL Statement in VB (ASP.NET) - asp.net

I have this SQL Statement:
de.SqlStatement = "SELECT A.Name, A.Catagory , COUNT(Patient_ID) AS PNO FROM PatientApplyToAssociation P INNER JOIN Association A on A.Association_ID = P.Association_ID WHERE A.Catagory='" & "health" & " '" & "' GROUP BY A.Name '"
with this Exception:
System.Data.SqlClient.SqlException was unhandled by user code
Class=16
ErrorCode=-2146232060
LineNumber=1
Message=Column
'Association.Name' is invalid in the select list because it is not
contained in either an aggregate function or the GROUP BY clause.
I had this exception when I added the where clause, It seems that the compiler cant see the Group By Section , because of the quotation ending before it, I tried to write it like this:
de.SqlStatement = "SELECT A.Name, A.Catagory , COUNT(Patient_ID) AS PNO FROM PatientApplyToAssociation P INNER JOIN Association A on A.Association_ID = P.Association_ID WHERE A.Catagory='" & "health" & "' GROUP BY A.Name '" & " '"
But it was an Incorrect syntax near ' '.
Any ideas?

I'm pretty sure you don't want the ' around the GROUP BY clause:
SELECT A.Name, A.Catagory
, COUNT(Patient_ID) AS PNO
FROM PatientApplyToAssociation P
INNER JOIN Association A
ON A.Association_ID = P.Association_ID
WHERE A.Catagory='" & "health" & " '" & " GROUP BY A.Name

In order to use the statement in your original question, you will need to revise it to be:
de.SqlStatement = "SELECT A.Name, A.Catagory, COUNT(1) AS PNO FROM PatientApplyToAssociation P INNER JOIN Association A on A.Association_ID = P.Association_ID WHERE A.Catagory='health' GROUP BY A.Name, A.Catagory"
There are 3 changes in this statement:
1) The extraneous string joins in the where and group by have been removed.
2) Group by A.Catagory has been added so that you will not receive another error similar to error in the question for this field.
3) COUNT(Patient_ID) has been changed to COUNT(1) as a possibly better practice. If the field you are counting contains nulls, it will not be included in the count. If this is the desired behavior, then your previous code was correct; otherwise you should use the revision.

Related

MS Access query, IIF function is returning error as "No value given for one or more required parameters"

I have Access query which does Union, group, get Maximum, Left Join and IIF(isNull) functions.
I have to union three subTables and group by column "mainid", get max-value from column "time" as "MaxSubTime" and mainid-column is filterd by mainTable.id.
Then I am applying LEFT Join MainTable to Union-Group.
If MaxSubTime is Null then i am applying the MainTable.endtime to MaxSubTime and getting it as "MaxMainTableEndTime".
till here everything works fine.
string myQry = "SELECT MainTable.id, MainTable.sttime, IIF(IsNULL(a.MaxSubTime), MainTable.endtime, a.MaxSubTime) AS MaxMainTableEndTime
FROM (MainTable LEFT JOIN (SELECT mainid, MAX(SubTime) AS MaxSubTime
FROM (SELECT Sub_table_1.mainid, Sub_table_1.time AS SubTime FROM Sub_table_1
UNION SELECT Sub_table_2.mainid, Sub_table_2.time AS SubTime Sub_table_2
UNION SELECT Sub_table_3.mainid, Sub_table_3.time AS SubTime Sub_table_3 GROUP BY mainid) AS a ON a.mainid = MainTable.id)
WHERE MaxMainTableEndTime >= #" + DateTime.Now + "# ";
But when i filter the final query by "MaxMainTableEndTime", i am getting this error "No value given for one or more required parameters".
Where i am doing mystake?
Me solved this issue by using "Having" clause and editing my code a little
string myQry = "SELECT MainTable.id, MainTable.sttime, a.MaxSubTime
FROM MainTable LEFT JOIN (SELECT mainid, MAX(SubTime) AS MaxSubTime
FROM(SELECT Sub_table_1.mainid, Sub_table_1.time AS SubTime FROM Sub_table_1
UNION SELECT Sub_table_2.mainid, Sub_table_2.time AS SubTime Sub_table_2
UNION SELECT Sub_table_3.mainid, Sub_table_3.time AS SubTime Sub_table_3
GROUP BY mainid HAVING MaxSubTime >= #" + DateTime.Now + "#)
AS a ON a.mainid = MainTable.id) WHERE MainTable.endtime >= #" + DateTime.Now + "# "

SQL query to update value in table to sum of attribute in another table, where the ID's match

I have tried several different queries and cannot seem to find one that works without causing an error
Incorrect syntax near keyword ' '
I have one table called Scores that saves the userID, week number, and that weeks score from a quiz.
Schema:
Scores (Id, userName, weekNumber, currentScore)
There are 12 weeks total, so in the end each user will have 12 entries in this table
I have another table Leaderboard that has schema :
Leaderboard (Id, userName, week1, week2, week3 ..... week12, totalScore)
Each user will only have one entry in this table.
I have been trying to save the sum of the currentScore from Scores into the totalScore attribute of Leaderboard and cannot seem to figure out the correct syntax.
My query is as follows:
UPDATE t1
SET t1.totalScore = t2.completeScore
FROM dbo.Leaderboard AS t1,
((SELECT Id, SUM(weeklyScore) AS completeScore FROM dbo.Scores) as F
INNER JOIN
(SELECT Id FROM dbo.Scores GROUP BY Id) AS S ON F.Id = S.Id) AS t2
WHERE t1.Id = t2.Id
Try this and let us know how it goes:
var total1 = ("UPDATE t1 " +
"SET t1.totalScore = t2.completeScore " +
"FROM dbo.Leaderboard AS t1, (SELECT F.Id, F.completeScore FROM " +
"(SELECT Id, SUM(weeklyScore) AS completeScore FROM dbo.Scores GROUP BY ID) as F " +
"INNER JOIN (SELECT Id FROM dbo.Scores/* GROUP BY Id*/) AS S "+
"ON F.Id = S.Id) AS t2 "+
"WHERE t1.Id = t2.Id");
By the way I think you were missing a GROUP BY clause in the definition of the F derived table and that you don't need the GROUP BY in the definition of the S derived table.

GROUP BY / Aggreggate function clarification

I have an SQL Query for each of my 2 Gridview elements. One is getting all the transactions by branch and transaction date:
SELECT
tb_TransactionDetails.TxnID,
tb_TransactionDetails.BranchCode,
tb_TransactionDetails.TxnDate,
tb_TransactionDetails.ReferenceNo,
tb_TransactionType.TxnTypeName,
tb_CurrencyCode.CCYDesc,
tb_TransactionDetails.CCYAmount,
tb_RecordStatus.StatusDesc,
(tb_TransactionName.FirstName + ' ' + ISNULL(tb_TransactionName.MiddleName,'') + ' ' + ISNULL(tb_TransactionName.LastName,'')) as 'Client',
(tb_TransactionName.AddressLine1 + ' ' + ISNULL(tb_TransactionName.AddressLine2, '') + ' ' + ISNULL(tb_TransactionName.AddressLine3, '')) as 'Address',
tb_TransactionName.WhoAdded,
tb_TransactionName.DateAdded,
ROW_NUMBER() OVER
(ORDER BY BranchCode ) AS RowNumber
FROM (((tb_TransactionType inner join tb_TransactionDetails
on tb_TransactionType.TxnTypeCode = tb_TransactionDetails.TxnType)
INNER JOIN tb_CurrencyCode on tb_TransactionDetails.CCYCode = tb_CurrencyCode.CCYCode)
inner join tb_RecordStatus on tb_TransactionDetails.RecordStatus = tb_RecordStatus.StatusCode)
LEFT JOIN tb_TransactionName
on tb_TransactionDetails.TxnID = tb_TransactionName.TxnID
WHERE BranchCode = '1003'
and TxnDate = '12/13/2013'
and one is getting all the users in the system:
select
USR.UserName,
USR.BranchID,
(ISNULL(USR.FirstName,'') + ' ' + ISNULL((SUBSTRING(USR.MiddleName,1,1) + '.' ),'') + ' ' + ISNULL(USR.LastName,'')) as 'Name',
MBS.IsLockedOut,
USR.LastActivityDate,
MAX(STUFF(fxMerge.RoleId, 1, 2, '')) as 'Roles'
from (aspnet_Membership as MBS inner join aspnet_Users as USR
on USR.ApplicationId = USR.ApplicationId and MBS.UserId = USR.UserId)
inner join aspnet_UsersInRoles UIR
on USR.UserId = UIR.UserId
CROSS APPLY(
SELECT ', ' + RoleName
FROM aspnet_UsersInRoles UIR1
INNER JOIN aspnet_Roles RM ON UIR1.RoleId = RM.RoleID
WHERE UIR.UserId = UIR1.UserId
FOR XML PATH('')) fxMerge (RoleId)
where USR.UserName = 'JSmith'
group by USR.UserName, USR.BranchID, USR.FirstName, USR.MiddleName, USR.LastName, MBS.IsLockedOut, USR.LastActivityDate
one thing I'm confused about, is that the 1st query does not need a GROUP BY clause, while the 2nd one does. My question is, why? I've been running the 1st query hundreds of times no problem in my system, without ever having the need of a GROUP BY clause, and the Gridview displays the expected results. While on my 2nd query, It's only when I add the long GROUP BY clause that the query executes successfully on the SQL Server Management studio, then nothing shows up on my Gridview.
That's because your second query has a MAX(). If you want the highest or lowest value, or the count or any other aggregate function, you'll need to specify how to group it.

Search the database to get date between

I have this select statement:
SELECT *
FROM Room
LEFT JOIN booking ON (Room.RoomId = booking.RoomId)
WHERE booking.Roomid is null
AND GETDATE() BETWEEN bookin.checkindate '" + TxtCheckIn.Text + "'
AND booking.checkoutdate '" + TxtCheckOut.Text + "'" + "
ORDER BY Room.RoomType
I want to check in the booking table if the date matches the checkin and checkout dates selected by users. If it doesn't match, the query should show all rooms in the room table (even if it is in the booking table), provided that they have different dates.
You need to determine whether any rows match the condition on the date. To do this, the following query moves the date condition into the on clause. Then it uses the window function count() to count the number of matches. If there are none, then all rows are returned. Otherwise, only matches are returned.
select t.*
from (SELECT *, count(booking.RoomId) over () as numMatches
FROM Room LEFT JOIN
booking
ON Room.RoomId = booking.RoomId and
GETDATE() BETWEEN booking.checkindate '" + TxtCheckIn.Text + "' and
booking.checkoutdate '" + TxtCheckOut.Text + "'" + "
) t
where numMatches > 0 and RoomId is not null or numMatches = 0
ORDER BY Room.RoomType

Dynamic order by in SqlDataSource by a dropdownlist and grid view

I have a grid view that connect to the DataSqlSource. I want to sort my queries dynamically by a dropdownlist. for example by date,name,family etc.
I also join some tables in my queries.
I use this code in my DataSqlSource:
SELECT AddTitle.Title, SubmitManuscript.Status, AddArticleType.Type, AddArticleType.UserName, AddArticleType.ArticleType, SubmitManuscript.date, SubmitManuscript.ArticleNum, AddArticleType.ArticleID, CONVERT (VARCHAR(10), SubmitManuscript.date, 103) AS date1, OtherWritter.ArticleID AS Expr1, OtherWritter.name, OtherWritter.family, AddArticleType.CheckFinish FROM AddArticleType INNER JOIN AddTitle ON AddArticleType.ArticleID = AddTitle.ArticleID INNER JOIN SubmitManuscript ON AddArticleType.ArticleID = SubmitManuscript.ArticleID INNER JOIN OtherWritter ON AddTitle.ArticleID = OtherWritter.ArticleID WHERE (AddArticleType.ArticleID IN (SELECT ArticleID FROM AddUpload_4 AS AddUpload_4_1 WHERE (AddArticleType.CheckFinish = '0'))) AND (AddArticleType.Type = #Type) AND (SubmitManuscript.Status = 'Accept') AND
(OtherWritter.MainAuthor = 'Yes') ORDER BY '[' + #SortOrder + ']' DESC
but it doesn't work for me and no sorting happen!
And I also try this code, this time it gave me an error:
here is the code:
SELECT ...
FROM ...
ORDER BY
CASE WHEN #order=Country THEN Country END DESC,
CASE WHEN #order= City THEN City END ASC,
CASE WHEN #order= name THEN name END ASC
Can any body help me?
I guess it should be:
SELECT ...
FROM ...
ORDER BY
CASE WHEN #order='Country' THEN Country END DESC,
CASE WHEN #order='City' THEN City END ASC,
CASE WHEN #order='name' THEN name END ASC

Resources