This is the first time im using caches. I set my local cache to true in my webconfig.When i try to run my login page is gives the following error
System.Data.SqlClient.SqlException occurred
HResult=0x80131904
Message=Maximum stored procedure, function, trigger, or view nesting level exceeded (limit 32).
Source=.Net SqlClient Data Provider
StackTrace:
it throws the error on the following code
lock (lastlevelLock)
{
DataSet retval = new DataSet();
if (UseLocalCache)
{
retval =Data.DataRepository.Provider.GetDetailsAll(); // this is where the error comes in
if (retval == null)
retval = new DataSet();
}
else
what am i doing wrong? because the exact same code and db works fine on other machines.I did look at the other similar errors mention on stackflow but nothing helped.
--WITH ENCRYPTION
AS
BEGIN
;WITH cte AS (
SELECT //do selection
FROM Table g WITH(NOLOCK)
)
SELECT //do selection
INTO #cte
FROM cte c
INNER JOIN list.Type gt WITH(NOLOCK) ON c.TypeId = gt.TypeID
INNER JOIN table.crumb br WITH(NOLOCK) ON c.ID = br.ID
ORDER BY Lev
SELECT
// select columns
NULL AS ResultExpected
INTO #TempGame
FROM #cte tg
JOIN list.Type gt WITH(NOLOCK) ON tg.TypeID = gt.TypeID
WHERE tg.ID IN (
SELECT ID FROM table2 WITH(NOLOCK)
WHERE ID = tg.ID
)
SELECT
//select columns
INTO #Temp2
FROM tanbe2 m WITH(NOLOCK)
INNER JOIN table g WITH(NOLOCK) ON m.ID = g.ID
//perform all joins
WHERE m.ID IN (SELECT ID FROM #Temp)
GETDATE() < ISNULL(m.ResultDateTime, m.ResultExpected)
SELECT * FROM #Temp
SELECT * FROM #Temp2
ORDER BY ResultExpected
DROP TABLE #cte
DROP TABLE #Temp
DROP TABLE #Temp2
END
GO
After searching and trying different solutions for multiple hours,i finally just restored the db AGAIN and it seemed to work.
Related
I am trying to make a sql query, that gets me the registration_timestamp of the newest comment.
By supplying a category id.
I have three tables. ( seen below with the fields that should be needed)
Ctm_Comments{
Id,
Page_ID,
Registration_Timestamp
}
Ctm_Forum_Categories{
Id
}
Ctm_Forum_Posts{
Id,
FK_Category_ID
}
I have tried the following, and it returns zero results.
var query = from p in Ctm_Forum_Posts
join c in Ctm_Forum_Categories on p.FK_Categori_ID equals c.Id
join ctm in Ctm_Comments on p.Id equals ctm.Page_ID
where c.Id == 1
select ctm.Reqistration_timestamp;
SQL Queries like these are not my strong suit, so i hope someone here can help out.
Ended up with this, based on the response from accepted answer.
var query = (from comments in Ctm_Comments
join posts in Ctm_Forum_Posts on comments.Page_ID equals posts.Id
join category in Ctm_Forum_Categories on posts.FK_Categori_ID equals category.Id
where category.Id == 1
orderby comments.Reqistration_timestamp descending
select comments.Reqistration_timestamp).FirstOrDefault();
SQL (MS SQL) Query needed is
SELECT TOP 1 [Registration_Timestamp]
FROM [dbo].[Ctm_Comments] AS C
INNER JOIN [dbo].[Ctm_Forum_Posts] AS P ON C.Page_ID = P.Id
INNER JOIN [dbo].[Ctm_Forum_Categories] AS CAT ON CAT.Id = P.Category_ID
WHERE CAT.Id = 1
ORDER BY C.Registration_Timestamp DESC
and this is if we accept that PageID (of Comments Table) is the Post Id. Otherwise, you are missing the PostId Column in the table of Comments which should be the join point
Run the Script below in SQL Server Studio for verification
CREATE TABLE [dbo].[Ctm_Comments] ( [Id] [int] NULL,[Page_ID] [int] NULL,[Registration_Timestamp] [datetime] NULL) ON [PRIMARY]
CREATE TABLE [dbo].[Ctm_Forum_Categories] ( [Id] [int] NULL) ON [PRIMARY]
CREATE TABLE [dbo].[Ctm_Forum_Posts] ( [Id] [int] NULL,[Category_ID] [int] NULL) ON [PRIMARY]
INSERT INTO [dbo].[Ctm_Comments] VALUES (1, 1, '2020-10-23 13:12:55')
INSERT INTO [dbo].[Ctm_Comments] VALUES (2, 1, '2020-10-26 12:12:55')
INSERT INTO [dbo].[Ctm_Comments] VALUES (3, 1, '2020-10-26 12:25:55')
INSERT INTO [dbo].[Ctm_Comments] VALUES (4, 1, '2020-10-26 13:12:55')
INSERT INTO [dbo].[Ctm_Forum_Categories] VALUES (1)
INSERT INTO [dbo].[Ctm_Forum_Posts] VALUES (1, 1)
SELECT TOP 1 [Registration_Timestamp]
FROM [dbo].[Ctm_Comments] AS C
INNER JOIN [dbo].[Ctm_Forum_Posts] AS P ON C.Page_ID = P.Id
INNER JOIN [dbo].[Ctm_Forum_Categories] AS CAT ON CAT.Id = P.Category_ID
WHERE CAT.Id = 1
ORDER BY C.Registration_Timestamp DESC
DROP TABLE [dbo].[Ctm_Comments]
DROP TABLE [dbo].[Ctm_Forum_Categories]
DROP TABLE [dbo].[Ctm_Forum_Posts]
the Result is 2020-10-26 13:12:55.000
When you fix the "my query returns 0 results" part, I'd suggest something like this:
var mostRecentCommentTimestamp = query.Max();
But as you've only selected timestamps, this can only tell you the max timestamp, nothing else about the comment
If you want the whole most recent comment swap the select for an order by descending on the timestamp and take the first*, or install morelinq and use their MaxBy
*Edit, like this:
var query = from p in Ctm_Forum_Posts
join c in Ctm_Forum_Categories on p.FK_Categori_ID equals c.Id
join ctm in Ctm_Comments on p.Id equals ctm.Page_ID
where c.Id == 1
orderby ctm.Reqistration_timestamp descending
select ctm;
var firstComment = query.First();
All this said, at the moment you say your query produces no results; you need to fix that (the joins are wrong, or there is no category 1, or the db is missing data) before you can get a max/orderby of anything
Is there a way to return only ONE record so that I can get all the column calls via the code below?
using (var reader = await command.ExecuteReaderAsync(CommandBehavior.SequentialAccess).ConfigureAwait(false))
{
DataTable dtResults = new DataTable();
dtResults.Load(reader);
return dtResults;
}
So right now this will return ALL X records from the query and I only need to return 1 record so I can plug the columns data types etc. into my Grid control.
We can't just add SELECT Top 1 because some of the queries start with a CTE etc.
We can't wrap it around another query because sometimes the query have Order Bys
We can't force the users to add a separate query that will mimic what we want to do.
Here is the error:
Msg 1033, Level 15, State 1, Line 40
The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified.
Here is the query:
SELECT TOP 1 *
FROM
(SELECT O.Department, O.ID
FROM dbo.table1 e
LEFT JOIN dbo.table2 O ON e.Department = O.Department
ORDER BY ID) x
If you need metadata only, use .ExecuteReader(System.Data.CommandBehavior.SchemaOnly)
If you want to read one row, use SQL's OFFSET/FETCH clause. They are appended at the end of the statement, so might work for your case.
https://learn.microsoft.com/en-us/sql/t-sql/queries/select-order-by-clause-transact-sql?view=sql-server-ver15
Note that you must provide some ordering clause.
SELECT
O.Department
,O.ID
FROM dbo.table1 e
LEFT JOIN dbo.table2 O
ON e.Department = O.Department
order by O.ID
OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY
Try the following, you cannot use Order by with sub-query in SQL server.
select top 1 *
from
(
SELECT
O.Department
,O.ID
FROM dbo.table1 e
LEFT JOIN dbo.table2 O
ON e.Department = O.Department
)
Order by
ID
The subquery is just unecessary. You can use top (1) and order by directly in the outer query:
select top(1) o.department, o.id
from dbo.table1 e
left join dbo.table2 o on e.department = o.department
order by id
sp_describe_first_result_set should do what you want. It'll return metadata for the command in question.
exec sp_describe_first_result_set #tsql = N'SELECT O.Department, O.ID
FROM dbo.table1 e
LEFT JOIN dbo.table2 O ON e.Department = O.Department
ORDER BY ID'
Gets all fields from Table but only the ones created last, for each different Field
SELECT t1.*
FROM Table AS t1
INNER JOIN (
SELECT Field
, MAX(CreatedOn) AS MaxDate
FROM Table
WHERE ImportedOn IS NULL
AND Status <> 'error'
GROUP BY Field) AS t2
ON t1.Field = t2.Field
AND t1.CreatedOn = t2.MaxDate
I read this data inside a while loop. At the end I try to update the same table - the same record read - and it gives me a timeout. I figure its because the table is blocked for changes.
My question is: How to work around it? Any way to 'fix' the query so it'll accept updates?
Extra info: If I query without JOIN it works perfectly.
Instead of doing an UPDATE row by row after every read; do a JOIN with the table and update. Something like below [A sample; not the exact query]
UPDATE t1
SET column_name = tab.some_column_name
FROM Table t1
JOIN
(
SELECT t1.*
FROM Table AS t1
INNER JOIN (
SELECT Field,
MAX(CreatedOn) AS MaxDate
FROM Table
WHERE ImportedOn IS NULL
AND Status <> 'error'
GROUP BY Field
) AS t2
ON t1.Field = t2.Field
AND t1.CreatedOn = t2.MaxDate
) tab
ON t1.Field = tab.Field
I'm attempting to combine the logic for some of my SQL queries, and I can't seem to figure out this problem. Obviously SQL Server CE has many limitations compared to SQL Server or mySQL, but surely there's a way to solve this.
I want to do a count on one table in my database, based on some parameters, and then I want to compare this value to a value stored in a column in another table.
Let's say the database is modeled like this:
Table1:
ID int
Key string
NumberInUse int
Table2:
ID int
OtherID int
Here's the necessary parts of the query.
SELECT *
FROM Table1
LEFT JOIN Table2 ON Table1.ID = Table2.ID
WHERE Table1.Key = #key
AND (SELECT COUNT(*) FROM Table2 WHERE ID = Table1.ID AND OtherID = #otherID) < Table1.NumberInUse;
Unfortunately this query gives me this error:
There was an error parsing the query. [ Token line number = 4,Token line offset = 6,Token in error = SELECT ]`
So is there a way I can rephrase the WHERE clause of my query to utilize this comparison?
Try this:
SELECT *
FROM Table1 t1
INNER JOIN (SELECT ID
,COUNT(*) numCount
FROM Table2 t2
WHERE t2.OtherId = #otherID
GROUP BY ID) t3
ON t1.ID = t3.ID
WHERE t1.Key = #Key
AND t3.numCount < t1.NumberInUse
Sure it's not SQL. You're missing the right operand of the second LEFT JOIN:
SELECT *
FROM Table1 LEFT JOIN Table2
ON Table1.ID = Table2.ID
LEFT JOIN ????? WHUT ?????
WHERE Table1.Key = #key
AND (SELECT COUNT(*) FROM Table2 WHERE ID = Table1.ID AND OtherID = #otherID) < Table1.NumberInUse;
So I have a many to many relationship between something known as Specialism and SpecialismCombo. What I'm trying to do is take an int[] of ids and check if there is a combo already that contains the specialisms with those ids.
I was close but not quite right.
Say I have specialisms with Ids 1 and 3 and I create a combo with those specialisms.
If I pass in 3 & 1 then it returns the expected combo id.
If I pass in 1 then it returns the combo id that has both 1 and 3.
I can't just rely on total number of specialisms associated with the combo. Because if a combo has two items, 1 and 4 and the items being matched on are 1 and 3 I don't want this coming back as a matched combo.
So it's like I do need the count of this result, and match the count of total specialisms associated to the combo. I don't quite get whether I'm after a subquery or detatchedcriteria or how to get the result I want using nhibernate criteria. Thanks for your help!
int[] SpecialismIds = ArrayExtensions.ConvertArray<int>(idCollection.Split(new char[] { '|' }));
ICriteria query = m_SpecialismComboRepository.QueryAlias("sc");
query.CreateAlias("sc.Specialisms", "s", NHibernate.SqlCommand.JoinType.InnerJoin);
ICriterion lastCriteria = null;
foreach(int i in SpecialismIds)
{
ICriterion currentCriteria = Restrictions.Eq("s.SpecialismId", i);
if (lastCriteria != null)
lastCriteria = Restrictions.Or(lastCriteria, currentCriteria);
else
lastCriteria = currentCriteria;
}
if (lastCriteria != null)
query.Add(lastCriteria);
IProjection IdCount = Projections.Count("s.SpecialismId").As("IdCount");
query.SetProjection(
Projections.GroupProperty("sc.SpecialismComboId"),
IdCount
);
query.Add(Restrictions.Eq(IdCount, SpecialismIds.Count()));
var comboId = query.List();
The sql being generated is:
SELECT this_.SpecialismComboId as y0_, count(s1_.SpecialismId) as y1_
FROM dbo.SpecialismCombo this_
inner join SpecialismComboSpecialism specialism3_ on this_.SpecialismComboId=specialism3_.SpecialismId
inner join dbo.Specialism s1_ on specialism3_.SpecialismComboId=s1_.SpecialismId WHERE s1_.SpecialismId = #p0
GROUP BY this_.SpecialismComboId HAVING count(s1_.SpecialismId) = #p1',N'#p0 int,#p1 int',#p0=3,#p1=1
EDIT - It seems like I either need the having to be something like...
HAVING count(s1_.SpecialismId) = (select count(SpecialismId)
from specialismComboSpecialism
where SpecialismComboId = y0
group by SpecialismComboId) == #p2
Or maybe it's simpler than that and I need to exclude SpecalismCombos where the combo.specialisms are not in the collection of ids.
Ie. if the combo has specialisms 1 and 3 but the collection only has 1.. then we could exclude this combo based on 3 not being in the collection…
Edit 8/8/2011
Went back to focusing on how to get the result I needed in SQL - and I believe this query works.
WITH CustomQuery AS
(
SELECT sc.SpecialismComboId,
count(s.SpecialismId) AS ItemCount
FROM SpecialismCombo sc
inner join SpecialismComboSpecialism scs on sc.SpecialismComboId = scs.SpecialismComboId
inner join Specialism s on s.SpecialismId = scs.SpecialismId
GROUP BY sc.SpecialismComboId
HAVING count(s.SpecialismId) = 2
)
SELECT CustomQuery.SpecialismComboId FROM CustomQuery
INNER JOIN SpecialismComboSpecialism scs on CustomQuery.SpecialismComboId = scs.SpecialismComboId
WHERE scs.SpecialismId in (1,4)
GROUP BY CustomQuery.SpecialismComboId
HAVING count(scs.SpecialismId) = 2
So now I just need to figure out how to call this procedure from my nhibernate code passing in the appropriate values :)
I also discovered in the process that my mapping class was wrong - as it was putting the wrong values in the mapping table (ie. the specialismid was ending up in the specialismcomboid field !)
Your solution should actually work well. The specialisms are filtered by id and there shouldn't be anything left that is not searched for, so count should work. Unless you have the same specialism joined more the once. This currentCriteria lastCriteria stuff looks a bit strange, may be there is an error. Just use Expression.In or Conjunction.
IProjection IdCount = Projections.Count("s.SpecialismId").As("IdCount");
IQuery query = session
.CreateCriteria<SpecialismCombo>("sc")
.CreateCriteria("Specialism", "s");
.Add(Expression.In("s.SpecialismId", SpecialismIds));
.SetProjection(
Projections.GroupProperty("sc.SpecialismComboId"),
IdCount);
.Add(Restrictions.Eq(IdCount, SpecialismIds.Count()));
Should result in a query like this:
select ...
from
SpecialismCombo sc
inner join -- linktable ...
inner join Specialism s on ...
where
s.SpecialismId in (1, 4)
Group By sc.SpecialismComboId
having count(*) = 2
The same in HQL
from SpecialismCombo sc
join sc.Specialism s
where s.id in (:ids)
group by sc
having count(*) = :numberOfIds
You could also join the specialism as many times as you have ids to find:
IQuery query = session.CreateCriteria<SpecialismCombo>("sc")
int counter = 0;
foreach(int id in ids)
{
string alias = "s" + counter++;
query
.CreateCriteria("Specialism", alias);
.Add(Expression.Eq(alias + ".SpecialismId", id));
}
should create a query like this:
select ...
from
SpecialismCombo sc
inner join -- linktable ...
inner join Specialism s0 on ...
inner join -- linktable ...
inner join Specialism s1 on ...
where
s0.SpecialismId = 1
and s1.SpecialismId = 4
So I ended up creating a stored proc and using SQL CTE in order to get only the specialism combos with the correct count of specialisms. Posting this in case someone else comes across a similar issue.
Rediscovered after 8 months of using nhibernate that I'd forgotten a lot of SQL stuff :)
DECLARE #IdCollectionCount INT
, #IdCollection VARCHAR(250)
, #CollectionDelimiter NVARCHAR
SET #IdCollectionCount = 2;
SET #IdCollection = '1,4';
SET #CollectionDelimiter= ',';
WITH CustomQuery AS
(
SELECT sc.SpecialismComboId,
count(s.SpecialismId) AS ItemCount
FROM SpecialismCombo sc
inner join SpecialismComboSpecialism scs on sc.SpecialismComboId = scs.SpecialismComboId
inner join Specialism s on s.SpecialismId = scs.SpecialismId
GROUP BY sc.SpecialismComboId
HAVING count(s.SpecialismId) = #IdCollectionCount
)
SELECT Top 1 CustomQuery.SpecialismComboId FROM CustomQuery
INNER JOIN SpecialismComboSpecialism scs on CustomQuery.SpecialismComboId = scs.SpecialismComboId
INNER JOIN dbo.fn_SplitDelimited(#IdCollection,#CollectionDelimiter) AS ids
ON scs.SpecialismId = CAST(ids.ListValue AS INT)
GROUP BY CustomQuery.SpecialismComboId
HAVING count(scs.SpecialismId) = #IdCollectionCount