Currently running queries in SQL Server [duplicate] - sql

This question already has answers here:
List the queries running on SQL Server
(17 answers)
Closed 7 years ago.
Is there a program or a sql query that I can find which SQL queries are being run on an SQL Server 2012? I think there was a tool in earlier version of SQL Server where the actual query content gets displayed or the stored procedure name?

I use the below query
SELECT SPID = er.session_id
,STATUS = ses.STATUS
,[Login] = ses.login_name
,Host = ses.host_name
,BlkBy = er.blocking_session_id
,DBName = DB_Name(er.database_id)
,CommandType = er.command
,ObjectName = OBJECT_NAME(st.objectid)
,CPUTime = er.cpu_time
,StartTime = er.start_time
,TimeElapsed = CAST(GETDATE() - er.start_time AS TIME)
,SQLStatement = st.text
FROM sys.dm_exec_requests er
OUTER APPLY sys.dm_exec_sql_text(er.sql_handle) st
LEFT JOIN sys.dm_exec_sessions ses
ON ses.session_id = er.session_id
LEFT JOIN sys.dm_exec_connections con
ON con.session_id = ses.session_id
WHERE st.text IS NOT NULL

Depending on your privileges, this query might work:
SELECT sqltext.TEXT,
req.session_id,
req.status,
req.command,
req.cpu_time,
req.total_elapsed_time
FROM sys.dm_exec_requests req
CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS sqltext
Ref: http://blog.sqlauthority.com/2009/01/07/sql-server-find-currently-running-query-t-sql

There's this, from SQL Server DMV's In Action book:
The output shows the spid (process identifier), the ecid (this is similar to a thread within the same spid and is useful for identifying queries running in parallel), the user running the SQL, the status (whether the SQL is running or waiting), the wait status (why it’s waiting), the hostname, the domain name, and the start time (useful for determining how long the batch has been running).
The nice part is the query and parent query. That shows, for example, a stored proc as the parent and the query within the stored proc that is running. It has been very handy for me. I hope this helps someone else.
USE master
GO
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
SELECT
er.session_Id AS [Spid]
, sp.ecid
, er.start_time
, DATEDIFF(SS,er.start_time,GETDATE()) as [Age Seconds]
, sp.nt_username
, er.status
, er.wait_type
, SUBSTRING (qt.text, (er.statement_start_offset/2) + 1,
((CASE WHEN er.statement_end_offset = -1
THEN LEN(CONVERT(NVARCHAR(MAX), qt.text)) * 2
ELSE er.statement_end_offset
END - er.statement_start_offset)/2) + 1) AS [Individual Query]
, qt.text AS [Parent Query]
, sp.program_name
, sp.Hostname
, sp.nt_domain
FROM sys.dm_exec_requests er
INNER JOIN sys.sysprocesses sp ON er.session_id = sp.spid
CROSS APPLY sys.dm_exec_sql_text(er.sql_handle)as qt
WHERE session_Id > 50
AND session_Id NOT IN (##SPID)
ORDER BY session_Id, ecid

here is what you need to install the SQL profiler http://msdn.microsoft.com/en-us/library/bb500441.aspx. However, i would suggest you to read through this one http://blog.sqlauthority.com/2009/08/03/sql-server-introduction-to-sql-server-2008-profiler-2/ if you are looking to do it on your Production Environment.
There is another better way to look at the queries watch this one and see if it helps
http://www.youtube.com/watch?v=vvziPI5OQyE

The tool is called the SQL Server Profiler, it's still part of the standard toolset.

You are talking about SQL Profiler.

Related

Msg 7202, Level 11, State 2, Line 1 Could not find server 'acct' in sys.servers

Would you know what could be the code error on query with my tables and server database connection, I normally list my query in the following format and today it provides me with the same continued error and only this query is displaying this type of error. My tables are referencing the correct database due to the reason that this is the only database that hods these tables. My query code listed below, maybe its missing something.
SELECT Distinct
'CA' AS 'Server'
, DATENAME(month, res.Move_in_Date) [MonthName]
, DATEPART(day, res.Move_in_Date) [Day]
, DATENAME(WEEKDAY, res.Move_in_Date) [Weekday]
, res.Move_in_Date
, res.Move_out_Date
, ge.Entity_Number
, bld.Building_Name
, addr.Address2
, addr.City
, addr.State
, addr.Zip_Code
, bld.Building_ID
, unts.Unit_Number
, res.First_Name
, res.Last_Name
, ge.Active AS GL_Entities_Active
, bld.Building_Active
FROM
acct.cam_ca.dbo.residents AS res
INNER JOIN
acct.cam_ca.dbo.units AS unts
ON res.Unit_ID = unts.Unit_ID
INNER JOIN
acct.cam_ca.dbo.addresses AS addr
INNER JOIN
acct.cam_ca.dbo.gl_entities AS ge
ON addr.Address_ID = ge.Address_ID
INNER JOIN
acct.cam_ca.dbo.buildings AS bld
ON ge.GL_Entity_ID = bld.GL_Entity_ID ON unts.Building_ID = bld.Building_ID
WHERE
ge.Active = 1
AND ge.Entity_Number = 1
AND bld.Building_Active = 1
AND res.Move_in_Date BETWEEN '20200101 00:00:00.000 AM' AND '20200707 11:59:59 PM'
ORDER BY
ent.Entity_Number
, res.Move_in_Date
As can be read from the error message the server mentioned in the query is not available in metadata view sys.servers.There are two possibilities,
The server "acct" is not available.
The server "acct" is defined but could have a different name
defined.
Troubleshoot by running queries Run the query below to list all available servers ,
select name,data_source from sys.servers
Try to identify the name corresponding to the data_source and use that name instead of acct for the server in your query.
If you are unable to identify a relevant entry, contact DBA to provide the details of the server.
Your query is trying to access tables on a different server, accessed through a linked server called acct. For example, in your code you have acct.cam_ca.dbo.residents. Here:
residents is the table name
dbo is the schema name
cam_ca is the database name
acct is the linked server name
Either the linked server used to exist but has been deleted by a DBA, or you are running your query on a different server from the one where it works and this new server does not have the acct linked server set up, or you have changed the query.

Query to identify who can make changes to SQL DB objects

I am looking for a query to run on SQL server to identify who can change DB objects structure (DLL) within a SQL server. Please help. Thank you.
You can look in the Default Trace:
SELECT TE.name AS EventName ,
T.DatabaseName ,
t.ObjectName,
t.NTDomainName ,
t.ApplicationName ,
t.LoginName ,
t.StartTime
FROM sys.traces tr
cross apply sys.fn_trace_gettable(CONVERT(VARCHAR(150),
( SELECT f.[value] FROM sys.fn_trace_getinfo(tr.id) f WHERE f.property = 2 )), DEFAULT) T
JOIN sys.trace_events TE ON T.EventClass = TE.trace_event_id
WHERE
tr.is_default = 1
and name like 'Object:%'
ORDER BY t.StartTime ;
Thanks for efforts. I found the following site which gives you multiple queries determining effective database engine permissions.
https://learn.microsoft.com/en-us/sql/relational-databases/security/authentication-access/determining-effective-database-engine-permissions?view=sql-server-2017

SQL Server MERGE statement reporting invalid column

I have this MERGE statement that works fine on one database server and I need to deploy it to another database server for a different country's office. I used RedGate's SQL Compare and both databases have what is required.
MERGE dbo.MfgGrouping AS Target
USING
(SELECT JC.job_number
, JC.Quote_NO
, PMG.MfgGroupingID
, SR.Description
, MG.GroupingNumber
, MG.GroupingDesc
, MG.Assigned
, MG.AssignedDate
, MG.AssignedBy
, MG.[Priority]
, P.Record_no
FROM dbo.Product AS P
INNER JOIN dbo.ProductMfgGrouping AS PMG ON P.Record_no = PMG.Record_no
INNER JOIN dbo.Job_Control AS JC ON P.Quote_NO = JC.Quote_NO
LEFT OUTER JOIN dbo.MfgGrouping AS MG ON PMG.MfgGroupingID = MG.MfgGroupingID
LEFT OUTER JOIN dbo.ShopRouting AS SR ON MG.ShopRoutingID = SR.ShopRoutingID
WHERE (JC.job_number = #SalesOrder)) AS Source
ON(Target.MfgGroupingID = Source.MfgGroupingID)
WHEN MATCHED
THEN
UPDATE
SET Target.GroupingNumber = Source.GroupingNumber,
Target.Assigned = Source.Assigned,
Target.AssignedDate = Source.AssignedDate,
Target.AssignedBy = Source.AssignedBy
WHEN NOT MATCHED BY TARGET
THEN
INSERT(GroupingNumber, Assigned, AssignedDate, AssignedBy, Record_no)
VALUES(1, Source.Assigned, Source.AssignedDate, Source.AssignedBy, Source.Record_no);
The problem that I'm experiencing is that I get an error:
invalid column name 'Record_no'
on the deployed database; but not on the original DB. Everything looks the same and good to me.
Can someone please shed some light on this?
The only difference is the original database is SQL Server 2014 and the deployed database is SQL Server 2008.
Thanks,
Jimmy

Select SQL View Slow with table alias

I am baffled as to why selecting my SQL View is so slow when using a table alias (25 seconds) but runs so much faster when the alias is removed (2 seconds)
-this query takes 25 seconds.
SELECT [Extent1].[Id] AS [Id],
[Extent1].[ProjectId] AS [ProjectId],
[Extent1].[ProjectWorkOrderId] AS [ProjectWorkOrderId],
[Extent1].[Project] AS [Project],
[Extent1].[SubcontractorId] AS [SubcontractorId],
[Extent1].[Subcontractor] AS [Subcontractor],
[Extent1].[ValuationNumber] AS [ValuationNumber],
[Extent1].[WorksOrderName] AS [WorksOrderName],
[Extent1].[NewGross],
[Extent1].[CumulativeGross],
[Extent1].[CreateByName] AS [CreateByName],
[Extent1].[CreateDate] AS [CreateDate],
[Extent1].[FinalDateForPayment] AS [FinalDateForPayment],
[Extent1].[CreateByEmail] AS [CreateByEmail],
[Extent1].[Deleted] AS [Deleted],
[Extent1].[ValuationStatusCategoryId] AS [ValuationStatusCategoryId]
FROM [dbo].[ValuationsTotal] AS [Extent1]
-this query takes 2 seconds.
SELECT [Id],
[ProjectId],
[Project],
[SubcontractorId],
[Subcontractor],
[NewGross],
[ProjectWorkOrderId],
[ValuationNumber],
[WorksOrderName],
[CreateByName],
[CreateDate],
[CreateByEmail],
[Deleted],
[ValuationStatusCategoryId],
[FinalDateForPayment],
[CumulativeGross]
FROM [dbo].[ValuationsTotal]
this is my SQL View code -
WITH ValuationTotalsTemp(Id, ProjectId, Project, SubcontractorId, Subcontractor, WorksOrderName, NewGross, ProjectWorkOrderId, ValuationNumber, CreateByName, CreateDate, CreateByEmail, Deleted, ValuationStatusCategoryId, FinalDateForPayment)
AS (SELECT vi.ValuationId AS Id,
v.ProjectId,
p.NAME,
b.Id AS Expr1,
b.NAME AS Expr2,
wo.OrderNumber,
SUM(vi.ValuationQuantity * pbc.BudgetRate) AS 'NewGross',
sa.ProjectWorkOrderId,
v.ValuationNumber,
up.FirstName + ' ' + up.LastName AS Expr3,
v.CreateDate,
up.Email,
v.Deleted,
v.ValuationStatusCategoryId,
sa.FinalDateForPayment
FROM dbo.ValuationItems AS vi
INNER JOIN dbo.ProjectBudgetCosts AS pbc
ON vi.ProjectBudgetCostId = pbc.Id
INNER JOIN dbo.Valuations AS v
ON vi.ValuationId = v.Id
INNER JOIN dbo.ProjectSubcontractorApplications AS sa
ON sa.Id = v.ProjectSubcontractorApplicationId
INNER JOIN dbo.Projects AS p
ON p.Id = v.ProjectId
INNER JOIN dbo.ProjectWorkOrders AS wo
ON wo.Id = sa.ProjectWorkOrderId
INNER JOIN dbo.ProjectSubcontractors AS sub
ON sub.Id = wo.ProjectSubcontractorId
INNER JOIN dbo.Businesses AS b
ON b.Id = sub.BusinessId
INNER JOIN dbo.UserProfile AS up
ON up.Id = v.CreateBy
WHERE ( vi.Deleted = 0 )
AND ( v.Deleted = 0 )
GROUP BY vi.ValuationId,
v.ProjectId,
p.NAME,
b.Id,
b.NAME,
wo.OrderNumber,
sa.ProjectWorkOrderId,
v.ValuationNumber,
up.FirstName + ' ' + up.LastName,
v.CreateDate,
up.Email,
v.Deleted,
v.ValuationStatusCategoryId,
sa.FinalDateForPayment)
SELECT Id,
ProjectId,
Project,
SubcontractorId,
Subcontractor,
NewGross,
ProjectWorkOrderId,
ValuationNumber,
WorksOrderName,
CreateByName,
CreateDate,
CreateByEmail,
Deleted,
ValuationStatusCategoryId,
FinalDateForPayment,
(SELECT SUM(NewGross) AS Expr1
FROM ValuationTotalsTemp AS tt
WHERE ( ProjectWorkOrderId = t.ProjectWorkOrderId )
AND ( t.ValuationNumber >= ValuationNumber )
GROUP BY ProjectWorkOrderId) AS CumulativeGross
FROM ValuationTotalsTemp AS t
Any ideas why this is?
The SQL query runs with table alias as this is generated from Entity Framework so I have no way of changing this. I will need to modify my SQL view to be able to handle the table alias without affecting performance.
The execution plans are very different.
The slow one has a part that leaps out as being problematic. It estimates a single row will be input to a nested loops join and result in a single scan of ValuationItems. In practice it ends up performing more than 1,000 such scans.
Estimated
Actual
SQL Server 2014 introduced a new cardinality estimator. Your fast plan is using it. This is shown in the XML as CardinalityEstimationModelVersion="120" Your slow plan isn't (CardinalityEstimationModelVersion="70").
So it looks as though in this case the assumptions used by the new estimator give you a better plan.
The reason for the difference is probably as the fast one is running cross database (references [ProbeProduction].[dbo].[ValuationsTotal]) and presumably the database you are executing it from has compatility level of 2014 so automatically gets the new CardinalityEstimator.
The slow one is executing in the context of ProbeProduction itself and I assume the compatibility level of that database must be < 2014 - so you are defaulting to the legacy cardinality estimator.
You can use OPTION (QUERYTRACEON 2312) to get the slow query to use the new cardinality estimator (changing the database compatibility mode to globally alter the behaviour shouldn't be done without careful testing of existing queries as it can cause regressions as well as improvements).
Alternatively you could just try and tune the query working within the limits of the legacy CE. Perhaps adding join hints to encourage it to use something more akin to the faster plan.
The two queries are different (column order!). It is reasonable to assume the first query uses an index and is therefore much faster. I doubt it has anything to do with the aliassing.
For grins would take out the where and give this a try?
I might be doing a bunch of loop joins and filtering at the end
This might get it to filter up front
FROM dbo.ValuationItems AS vi
INNER JOIN dbo.Valuations AS v
ON vi.ValuationId = v.Id
AND vi.Deleted = 0
AND v.Deleted = 0
-- other joins
-- NO where
If you have a lot of loop joins going on then try inner hash join (on all)

Get last 10 execution time of a query in Sql Server 2012

With this query I'm getting the top 10 slow queries in Sql Server.
SELECT TOP 20
SUBSTRING(qt.text, (qs.statement_start_offset/2)+1,
((CASE qs.statement_end_offset WHEN -1 THEN DATALENGTH(qt.text)
ELSE qs.statement_end_offset
END - qs.statement_start_offset)/2)+1),
qs.execution_count,
qs.total_logical_reads, qs.last_logical_reads,
qs.min_logical_reads, qs.max_logical_reads,
qs.total_elapsed_time, qs.last_elapsed_time,
qs.min_elapsed_time, qs.max_elapsed_time,
qs.last_execution_time,
qp.query_plan
FROM
sys.dm_exec_query_stats qs
CROSS APPLY
sys.dm_exec_sql_text(qs.sql_handle) qt
CROSS APPLY
sys.dm_exec_query_plan(qs.plan_handle) qp
WHERE
qt.encrypted = 0
ORDER BY
qs.total_logical_reads DESC
What I want to do is finding each queries last 10 execution time.
Or an average execution period in a day makes me glad.
You can create snapshots of your database procedure executions at certain period of time and then you can compare them. Use the sql in order to insert into table every snapshot.
SELECT
getDAte() as SnapshotDate,
s.database_id,
s.[plan_handle],
s.[object_id],
s.last_execution_time,
s.execution_count,
s.total_worker_time,
s.last_worker_time,
s.min_worker_time,
s.max_worker_time,
s.total_physical_reads,
s.last_physical_reads,
s.min_physical_reads,
s.max_physical_reads,
s.total_logical_writes,
s.last_logical_writes,
s.min_logical_writes,
s.max_logical_writes,
s.total_logical_reads,
s.last_logical_reads,
s.min_logical_reads,
s.max_logical_reads,
s.total_elapsed_time,
s.last_elapsed_time,
s.min_elapsed_time,
s.max_elapsed_time
FROM sys.dm_exec_procedure_stats AS s
WHERE s.database_id NOT IN
(
DB_ID('master'),
DB_ID(N'tempdb'),
DB_ID(N'model'), DB_ID(N'msdb'),
32767 -- RESOURCE db
) ;
If you want to check that is running slowly and why, check Standard reports in SSMS.