I basically want to replicate this (from oracle):
https://databaseline.tech/how-to-multiply-across-a-hierarchy-in-oracle-part-1/
In Snowflake using connect by. First of all, I haven't found any documentation that tells me if I can (or how to) use aggregate functions with connect by.
Second, I've tried to replicate the code from the post above in Snowflake:
SELECT LEVEL
,o.id
,o.yield
,(
SELECT ROUND( EXP(SUM(LN(i.yield))), 2 ) -- only two significant digits
FROM hierarchy_example i
START WITH i.id = o.id -- start with the row from the outer query
CONNECT BY i.id = PRIOR i.prior_id -- reverse direction of PRIOR to go back up
) AS yield_to_step
,connect_by_root o.id AS root_id
,sys_connect_by_path(o.id, '->') as path
FROM hierarchy_example o
START WITH o.prior_id IS NULL -- start with anchor rows
CONNECT BY o.prior_id = PRIOR o.ID -- go down hierarchy
But when I run it I get this error:
000603 (XX000): SQL execution internal error:
Processing aborted due to error 370001:416518821; incident 8391142.
So does anyone how to do this in Snowflake or if it is even possible?
Related
There was some performance issue in my application in production, I did some investigation and found out that one process is blocking my SP execution. I saw the log in SolarWinds DPA and found out that the process having id 12345 is blocking my SP. then it is showing the query in SQL text.
Query which is blocking
SELECT ColX, ColY.........
FROM [dbo].[Table1] As T1
INNER JOIN [dbo].[Table2] AS T2
ON T1.[PaymentFK] = T2.[PaymentPK]
WHERE (([Col1] = #p0)
OR ([ExtBCol1atchFileFK] IS NULL))
AND ([Col2] = #p1)
AND ([Col3] = #p2)
AND (NOT ([Col4] = 1))
But not giving object names like SP/View/Trigger/Job. I searched this text in all the SPs/Views/Triggers. But could not find the blocking query.
So is there any way to find out in which object exactly this query is being used?
This might help if the script is stored in the database.
SELECT DISTINCT OBJECT_SCHEMA_NAME(object_id), OBJECT_NAME(object_id)
FROM sys.sql_modules (NOLOCK)
WHERE definition LIKE '%search_phrase%'
I Imported 2 tables into Microsoft SQL Server, I am able to perform operations on both the tables but the second table is not being detected by intellisense. I am able to perform queries using the second table, except the below one.
The code that I am trying to execute is this.
SELECT
dea.continent, dea.location, dea.date, dea.population,
vac.new_vaccinations,
SUM(CONVERT(int, vac.new_vaccinations)) OVER (PARTITION BY dea.Location
ORDER BY dea.location, dea.Date) AS RollingPeopleVaccinated,
--, (RollingPeopleVaccinated/population)*100
FROM
PortfolioProject..CovidDeaths dea
JOIN
PortfolioProject..CovidVaccinations vac ON dea.location = vac.location
AND dea.date = vac.date
WHERE
dea.continent IS NOT NULL
ORDER BY
2, 3
I am getting the error that I need to convert the data type of a column, I am doing it using this code SUM(CONVERT(int, vac.new_vaccinations)) but that is not being detected.
What could be the reason?
I found the following queries on the internet. The first query is for receiving 100 queries executed on the server,
SELECT TOP 100
deqs.last_execution_time AS [Time],
dest.text AS [Query] , *
FROM
sys.dm_exec_query_stats AS deqs
CROSS apply
sys.dm_exec_sql_text(deqs.sql_handle) AS dest
ORDER BY
deqs.last_execution_time DESC
and the second query displays the users registered in SQL Server.
SELECT * FROM sys.sql_logins
My question is how can I connect these two queries in such a way that it shows the users who have run the queries in the list. Thanks ...
As Charlieface says in the comments, you should set up Auditing to track who is executing what query & when. You can find information about SQL Server Auditing, including how to set it up, on Microsoft Docs: https://learn.microsoft.com/en-us/sql/relational-databases/security/auditing/sql-server-audit-database-engine
Once you have auditing set up as you want it, you can then execute the following to find the details of the most recent 100 queries:
SELECT TOP 100 *
FROM sys.fn_get_audit_file ('\\serverName\foldername\filename.sqlaudit',default,default)
ORDER BY event_time DESC;
I have written, and rewritten, a hospital census query for which I would like to create a daily Windows File Share subscription. The query seems fine; it runs properly in SSMS, BIDS, and on the SSRS Report Server itself. However, when I create any kind of subscription, sometimes the report will have old and incorrect data on it. There is no real pattern to when the report generates incorrectly, as far as I can tell, but the data that gets sent incorrectly is consistently the same, and is from back in January. I had initially written the query on a test server with the same data, just a little bit older, and had changed the dates that it would run for. I also had to re-deploy the report a few times after making changes. I had initially deployed it from the test system directly to the live server, so I tried completely redoing it in the live system, in addition to making some changes improve performance, but I am still getting the same incorrect data.
Any ideas would be greatly appreciated at this point, because I am at a loss and I am really just getting started with SQL.
Thank you for any assistance.
Edits: adding the queries that are returning the inconsistent data; removing my comments that have poorly-formatted code.
Also, to be a bit more specific about the issue: The subscription sometimes sends the census data for the day before as expected, and sometimes it sends the census data from January 15, and this only happens in the subscription.
Query 1:
SELECT
V.Name AS PatientName
,V.AccountNumber AS AccountNumber
,V.FinancialClassName AS FinancialClass
,V.ServiceDateTime
,P.EmergencyID AS Provider
,X.ErDateTime AS Discharge
,X.ErDispositionID AS Disposition
FROM dbo.AdmVisits AS V
INNER JOIN dbo.AdmProviders AS P
ON P.VisitID=V.VisitID
INNER JOIN dbo.AdmDischarge AS X
ON V.VisitID=X.VisitID
WHERE CAST(V.ServiceDateTime AS DATE)=CAST(DATEADD(day,-1,GETDATE()) AS DATE)
OR CAST(X.ErDateTime AS DATE)=CAST(DATEADD(day,-1,GETDATE()) AS DATE)
ORDER BY V.Name
Query 2:
SELECT
V.Name
,V.AccountNumber
,V.FinancialClassName
,V.InpatientServiceID
,V.RoomID
,D.AdmitDateTime
,P.AdmitID
,P.AttendID
,X.DischargeDateTime
,X.DispositionName
FROM dbo.AdmVisits AS V
INNER JOIN dbo.AdmittingData AS D
ON V.VisitID=D.VisitID
INNER JOIN dbo.AdmProviders AS P
ON P.VisitID=D.VisitID
LEFT OUTER JOIN dbo.AdmDischarge AS X
ON V.VisitID=X.VisitID
WHERE V.InpatientOrOutpatient='I'
AND NOT V.InpatientServiceID='INP LTC'
AND (CAST(D.AdmitDateTime AS DATE)<CAST(GETDATE()AS DATE))
AND (V.Status='ADM IN' OR CAST(X.DischargeDateTime AS DATE)=CAST(DATEADD(DAY,-1,GETDATE()) AS DATE))
ORDER BY V.Name
Query 3:
SELECT
V.Name
,V.AccountNumber
,V.FinancialClassName
,V.InpatientServiceID
,V.RoomID
,D.AdmitDateTime
,P.AdmitID
,P.AttendID
,X.DischargeDateTime
,X.DispositionName
,CASE
WHEN V.LoaStatus IN('F','L') THEN CAST(V.LoaEffectiveDateTime AS varchar)
Else 'No'
END AS 'LeaveOfAbsence'
FROM dbo.AdmVisits AS V
INNER JOIN dbo.AdmittingData AS D
ON V.VisitID=D.VisitID
INNER JOIN dbo.AdmProviders AS P
ON P.VisitID=D.VisitID
LEFT OUTER JOIN dbo.AdmDischarge AS X
ON V.VisitID=X.VisitID
WHERE V.InpatientServiceID='INP LTC'
AND (CAST(D.AdmitDateTime AS DATE)<CAST(GETDATE()AS DATE))
AND (V.Status='ADM IN' OR CAST(X.DischargeDateTime AS DATE)=CAST(DATEADD(DAY,-1,GETDATE()) AS DATE))
ORDER BY V.Name
So it turns out that the issue was the data source's connection string to the server. I was using 'localhost' instead of the server's actual name, and since the test and live servers are basically clones of one another, I think it wasn't consistently connecting to the right server. Not sure how exactly that works, but the report is working now.
We starting to get a lot of stored procedures in our application. Many of them are for custom reports many of which are no longer used. Does anyone know of a query we could run on the system views in SQL Server 2005 that would tell us the last date a stored procedure was executed?
The below code should do the trick (>= 2008)
SELECT o.name,
ps.last_execution_time
FROM sys.dm_exec_procedure_stats ps
INNER JOIN
sys.objects o
ON ps.object_id = o.object_id
WHERE DB_NAME(ps.database_id) = ''
ORDER BY
ps.last_execution_time DESC
Edit 1 : Please take note of Jeff Modens advice below. If you find a procedure here, you can be sure that it is accurate. If you do not then you just don't know - you cannot conclude it is not running.
In a nutshell, no.
However, there are "nice" things you can do.
Run a profiler trace with, say, the stored proc name
Add a line each proc (create a tabel of course)
"INSERT dbo.SPCall (What, When) VALUES (OBJECT_NAME(##PROCID), GETDATE()"
Extend 2 with duration too
There are "fun" things you can do:
Remove it, see who calls
Remove rights, see who calls
Add RAISERROR ('Warning: pwn3d: call admin', 16, 1), see who calls
Add WAITFOR DELAY '00:01:00', see who calls
You get the idea. The tried-and-tested "see who calls" method of IT support.
If the reports are Reporting Services, then you can mine the RS database for the report runs if you can match code to report DataSet.
You couldn't rely on DMVs anyway because they are reset om SQL Server restart.
Query cache/locks are transient and don't persist for any length of time.
Oh, be careful now! All that glitters is NOT gold! All of the “stats” dm views and functions have a problem for this type of thing. They only work against what is in cache and the lifetime of what is in cache can be measured in minutes. If you were to use such a thing to determine which SPs are candidates for being dropped, you could be in for a world of hurt when you delete SPs that were used just minutes ago.
The following excerpts are from Books Online for the given dm views…
sys.dm_exec_procedure_stats
Returns aggregate performance statistics for cached stored procedures. The view contains one row per stored procedure, and the lifetime of the row is as long as the stored procedure remains cached. When a stored procedure is removed from the cache, the corresponding row is eliminated from this view.
sys.dm_exec_query_stats
The view contains one row per query statement within the cached plan, and the lifetime of the rows are tied to the plan itself. When a plan is removed from the cache, the corresponding rows are eliminated from this view.
sys.dm_exec_procedure_stats contains the information about the execution functions, constraints and Procedures etc. But the life time of the row has a limit, The moment the execution plan is removed from the cache the entry will disappear.
Use [yourDatabaseName]
GO
SELECT
SCHEMA_NAME(sysobject.schema_id),
OBJECT_NAME(stats.object_id),
stats.last_execution_time
FROM
sys.dm_exec_procedure_stats stats
INNER JOIN sys.objects sysobject ON sysobject.object_id = stats.object_id
WHERE
sysobject.type = 'P'
ORDER BY
stats.last_execution_time DESC
This will give you the list of the procedures recently executed.
If you want to check if a perticular stored procedure executed recently
SELECT
SCHEMA_NAME(sysobject.schema_id),
OBJECT_NAME(stats.object_id),
stats.last_execution_time
FROM
sys.dm_exec_procedure_stats stats
INNER JOIN sys.objects sysobject ON sysobject.object_id = stats.object_id
WHERE
sysobject.type = 'P'
and (sysobject.object_id = object_id('schemaname.procedurename')
OR sysobject.name = 'procedurename')
ORDER BY
stats.last_execution_time DESC
If you enable Query Store on SQL Server 2016 or newer you can use the following query to get last SP execution. The history depends on the Query Store Configuration.
SELECT
ObjectName = '[' + s.name + '].[' + o.Name + ']'
, LastModificationDate = MAX(o.modify_date)
, LastExecutionTime = MAX(q.last_execution_time)
FROM sys.query_store_query q
INNER JOIN sys.objects o
ON q.object_id = o.object_id
INNER JOIN sys.schemas s
ON o.schema_id = s.schema_id
WHERE o.type IN ('P')
GROUP BY o.name , + s.name
This works fine on 2005 (if the plan is in the cache)
USE YourDb;
SELECT qt.[text] AS [SP Name],
qs.last_execution_time,
qs.execution_count AS [Execution Count]
FROM sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS qt
WHERE qt.dbid = DB_ID()
AND objectid = OBJECT_ID('YourProc')
I use this:
use YourDB;
SELECT
object_name(object_id),
last_execution_time,
last_elapsed_time,
execution_count
FROM
sys.dm_exec_procedure_stats ps
where
lower(object_name(object_id)) like 'Appl-Name%'
order by 1