what were the last few queries ran on SQL Server ? - sql-server

what were the last few queries ran on SQL Server and with client name (system name) ?
i am running this query in server side
below query getting queries
SELECT 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
how can i get system name
for e.g
time | query | System Name

You could check the sp_who and sp_who2 text.
create procedure sys.sp_who2 --- 1995/11/03 10:16
#loginame sysname = NULL
as
set nocount on
declare
#retcode int
declare
#sidlow varbinary(85)
,#sidhigh varbinary(85)
,#sid1 varbinary(85)
,#spidlow int
,#spidhigh int
declare
#charMaxLenLoginName varchar(6)
,#charMaxLenDBName varchar(6)
,#charMaxLenCPUTime varchar(10)
,#charMaxLenDiskIO varchar(10)
,#charMaxLenHostName varchar(10)
,#charMaxLenProgramName varchar(10)
,#charMaxLenLastBatch varchar(10)
,#charMaxLenCommand varchar(10)
declare
#charsidlow varchar(85)
,#charsidhigh varchar(85)
,#charspidlow varchar(11)
,#charspidhigh varchar(11)
-- defaults
select #retcode = 0 -- 0=good ,1=bad.
select #sidlow = convert(varbinary(85), (replicate(char(0), 85)))
select #sidhigh = convert(varbinary(85), (replicate(char(1), 85)))
select
#spidlow = 0
,#spidhigh = 32767
--------------------------------------------------------------
IF (#loginame IS NULL) --Simple default to all LoginNames.
GOTO LABEL_17PARM1EDITED
-- select #sid1 = suser_sid(#loginame)
select #sid1 = null
if exists(select * from sys.syslogins where loginname = #loginame)
select #sid1 = sid from sys.syslogins where loginname = #loginame
IF (#sid1 IS NOT NULL) --Parm is a recognized login name.
begin
select #sidlow = suser_sid(#loginame)
,#sidhigh = suser_sid(#loginame)
GOTO LABEL_17PARM1EDITED
end
--------
IF (lower(#loginame collate Latin1_General_CI_AS) IN ('active')) --Special action, not sleeping.
begin
select #loginame = lower(#loginame collate Latin1_General_CI_AS)
GOTO LABEL_17PARM1EDITED
end
--------
IF (patindex ('%[^0-9]%' , isnull(#loginame,'z')) = 0) --Is a number.
begin
select
#spidlow = convert(int, #loginame)
,#spidhigh = convert(int, #loginame)
GOTO LABEL_17PARM1EDITED
end
--------
raiserror(15007,-1,-1,#loginame)
select #retcode = 1
GOTO LABEL_86RETURN
LABEL_17PARM1EDITED:
-------------------- Capture consistent sysprocesses. -------------------
select
spid
,status
,sid
,hostname
,program_name
,cmd
,cpu
,physical_io
,blocked
,dbid
,convert(sysname, rtrim(loginame))
as loginname
,spid as 'spid_sort'
, substring( convert(varchar,last_batch,111) ,6 ,5 ) + ' '
+ substring( convert(varchar,last_batch,113) ,13 ,8 )
as 'last_batch_char'
,request_id
into #tb1_sysprocesses
from sys.sysprocesses_ex with (nolock)
if ##error <> 0
begin
select #retcode = ##error
GOTO LABEL_86RETURN
end
--------Screen out any rows?
if (#loginame in ('active'))
delete #tb1_sysprocesses
where lower(status) = 'sleeping'
and upper(cmd) in (
'AWAITING COMMAND'
,'LAZY WRITER'
,'CHECKPOINT SLEEP'
)
and blocked = 0
--------Prepare to dynamically optimize column widths.
select
#charsidlow = convert(varchar(85),#sidlow)
,#charsidhigh = convert(varchar(85),#sidhigh)
,#charspidlow = convert(varchar,#spidlow)
,#charspidhigh = convert(varchar,#spidhigh)
select
#charMaxLenLoginName =
convert( varchar
,isnull( max( datalength(loginname)) ,5)
)
,#charMaxLenDBName =
convert( varchar
,isnull( max( datalength( rtrim(convert(varchar(128),db_name(dbid))))) ,6)
)
,#charMaxLenCPUTime =
convert( varchar
,isnull( max( datalength( rtrim(convert(varchar(128),cpu)))) ,7)
)
,#charMaxLenDiskIO =
convert( varchar
,isnull( max( datalength( rtrim(convert(varchar(128),physical_io)))) ,6)
)
,#charMaxLenCommand =
convert( varchar
,isnull( max( datalength( rtrim(convert(varchar(128),cmd)))) ,7)
)
,#charMaxLenHostName =
convert( varchar
,isnull( max( datalength( rtrim(convert(varchar(128),hostname)))) ,8)
)
,#charMaxLenProgramName =
convert( varchar
,isnull( max( datalength( rtrim(convert(varchar(128),program_name)))) ,11)
)
,#charMaxLenLastBatch =
convert( varchar
,isnull( max( datalength( rtrim(convert(varchar(128),last_batch_char)))) ,9)
)
from
#tb1_sysprocesses
where
spid >= #spidlow
and spid <= #spidhigh
--------Output the report.
EXEC(
'
SET nocount off
SELECT
SPID = convert(char(5),spid)
,Status =
CASE lower(status)
When ''sleeping'' Then lower(status)
Else upper(status)
END
,Login = substring(loginname,1,' + #charMaxLenLoginName + ')
,HostName =
CASE hostname
When Null Then '' .''
When '' '' Then '' .''
Else substring(hostname,1,' + #charMaxLenHostName + ')
END
,BlkBy =
CASE isnull(convert(char(5),blocked),''0'')
When ''0'' Then '' .''
Else isnull(convert(char(5),blocked),''0'')
END
,DBName = substring(case when dbid = 0 then null when dbid <> 0 then db_name(dbid) end,1,' + #charMaxLenDBName + ')
,Command = substring(cmd,1,' + #charMaxLenCommand + ')
,CPUTime = substring(convert(varchar,cpu),1,' + #charMaxLenCPUTime + ')
,DiskIO = substring(convert(varchar,physical_io),1,' + #charMaxLenDiskIO + ')
,LastBatch = substring(last_batch_char,1,' + #charMaxLenLastBatch + ')
,ProgramName = substring(program_name,1,' + #charMaxLenProgramName + ')
,SPID = convert(char(5),spid) --Handy extra for right-scrolling users.
,REQUESTID = convert(char(5),request_id)
from
#tb1_sysprocesses --Usually DB qualification is needed in exec().
where
spid >= ' + #charspidlow + '
and spid <= ' + #charspidhigh + '
-- (Seems always auto sorted.) order by spid_sort
SET nocount on
'
)
LABEL_86RETURN:
if (object_id('tempdb..#tb1_sysprocesses') is not null)
drop table #tb1_sysprocesses
return #retcode -- sp_who2
Hope this helps.

The below query should help you:
SELECT conn.session_id, sson.host_name, sson.login_name,
sqltxt.text, sson.login_time, sson.status
FROM sys.dm_exec_connections conn
INNER JOIN sys.dm_exec_sessions sson
ON conn.session_id = sson.session_id
CROSS APPLY sys.dm_exec_sql_text(most_recent_sql_handle) AS sqltxt
ORDER BY conn.session_id desc
Source: http://www.sqlservercurry.com/2011/12/last-run-query-in-sql-server.html

Related

Optimise a Stored procedure in SQL? Facing Error

Can someone help me to optimise this SP as it takes more than 3 minutes to run and then it gives Timeout error. "Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding." I am a beginner and would like to optimise the below SP because it takes forever to give results and it also gives timeout error. I tried putting indexing to temp tables but unsuccessful. Help !!!!
ALTER PROCEDURE GetCompanyByCandidatetest
#USER_ID VARCHAR(50) = NULL
AS
BEGIN
declare #statenew varchar(1000) = Null
declare #countnew varchar(1000) = Null
declare #STRSQLNew varchar(max)
declare #STRSQL4 varchar(max)
declare #state1 varchar(1000) = Null ,#ind varchar(1000) = Null,#Distinct varchar(1000) = Null,#Dist1 varchar(1000) = Null,
#EQuit_ID varchar(1000) = Null,#Degree_ID varchar(100) = Null,#Isguest varchar(100) = Null,#verified varchar(100) = Null,
#keyword varchar(100) = Null,#workexperience varchar(100) = Null,#prefcity varchar(100) = Null,#addcity varchar(100) = Null,
#Key_skill varchar(100) = Null,#CURRENT_DEPARTMENT varchar(100),#PREF_DEPARTMENT varchar(100),#CURRENT_DESIGNATION varchar(100),#PREF_DESIGNATION varchar(100),#indcurr varchar(100)
select #Isguest = isnull(guest_login,0), #verified = isnull(VERIFIED,0) from mtb_frinds where user_id = #USER_ID
select #statenew = isnull(PREF_STATE,''),#state1 = isnull(ADD_STATE,''),#Distinct = isnull(PREF_DISTRICT,''),#Distinct1 = isnull(add_dist,''),
#ind = isnull(PREF_INDUSTRY,''),#indcurr=isnull(CURRENT_INDUSTRY,'') ,#EQuit_ID = isnull(EQ_ID,'') ,#keyword=isnull(key_word,'') ,#workexperience=isnull(WORK_EXPYEARS,''),#CURRENT_DEPARTMENT=isnull(CURRENT_DEPARTMENT,''), #PREF_DEPARTMENT=isnull(PREF_DEPARTMENT,''),
#prefcity=isnull(PREF_CITY,'') ,#addcity=ADD_CITY,#Key_skill=isnull(Key_skill,''),#CURRENT_DESIGNATION=isnull(CURRENT_DESIGNATION,''),#PREF_DESIGNATION=isnull(PREF_DESIGNATION,'')
from mtb_frinds where USER_ID = #USER_ID
if(#statenew!='' and #Key_skill !='' and #state1 !='' and #keyword !='' )
begin
print 'ind' +#ind
print '#indcurr' +#indcurr
print '#PREF_DEPARTMENT'+ #PREF_DEPARTMENT
print '#CURRENT_DEPARTMENT'+#CURRENT_DEPARTMENT
print '#keyword'+ #keyword
set #STRSQLNew='
select ej_id, EQ_ID, JOB_STATUS ,job_desc,
active, USER_ID, JOB_TITLE, CREATED_ON,
REQUIRED_MP, WORK_EXPYEARS, SALARY, IND_ID,
Key_skill, STATE_ID, DIST_ID, LOCALITY_ID,
DEPT_ID,1 as Priority, EXPIRATION_DATE
into #dummy from mtb_jobs Ek
'
IF #EQuit_ID IS NOT NULL AND #EQuit_ID != ''
BEGIN
print 1
SET #STRSQLNew = #STRSQLNew + ' CROSS APPLY dbo.Split(EQ_ID,'','') AS A
CROSS APPLY dbo.Split('''+#EQuit_ID+''','','') AS B'
set #STRSQL4 ='(((A.items = B.items) or '
END
IF #keyword IS NOT NULL AND #keyword != ''
BEGIN
print 2
SET #STRSQLNew = #STRSQLNew + ' CROSS APPLY dbo.Split(keywords,'','') AS e
CROSS APPLY dbo.Split('''+#keyword+''','','') AS f'
set #STRSQL4 =#STRSQL4+'(e.items =f.items)) and '
END
IF #statenew IS NOT NULL AND #statenew != ''
BEGIN
print 3
SET #STRSQLNew = #STRSQLNew + ' CROSS APPLY dbo.Split(STATE_ID,'','') AS i
CROSS APPLY dbo.Split('''+#statenew+''','','') AS j'
set #STRSQL4 = #STRSQL4+'((i.items =j.items) '
END
IF #state1 IS NOT NULL AND #state1 != ''
BEGIN
print 4
SET #STRSQLNew = #STRSQLNew + ' CROSS APPLY dbo.Split(STATE_ID,'','') AS k
CROSS APPLY dbo.Split('''+#state1+''','','') AS l'
set #STRSQL4 =#STRSQL4+' or (k.items =l.items)) and '
END
IF #Key_skill IS NOT NULL AND #Key_skill != ''
BEGIN
print 5
SET #STRSQLNew = #STRSQLNew + ' CROSS APPLY dbo.Split(Key_skill,'','') AS g
CROSS APPLY dbo.Split('''+#Key_skill+''','','') AS h'
set #STRSQL4 =#STRSQL4+' ((g.items =h.items) or
'
END
set #STRSQLNew = #STRSQLNew+ ' where '+ #STRSQL4 +'(DEPT_ID in (select items from dbo.split('''+#CURRENT_DEPARTMENT+''','','')) or DEPT_ID in (select items from dbo.split('''+#PREF_DEPARTMENT+''','','')))))
or(e.items =f.items and ((k.items =l.items) or (i.items =j.items) ))
'
set #STRSQLNew =#STRSQLNew+ ' select * into #temp from ( select max(ej_id) as ej_id , max(EQ_ID) as EQ_ID, max(JOB_STATUS) as JOB_STATUS , max(job_desc) as job_desc,max(active) as active, max(USER_ID) as USER_ID ,max(JOB_TITLE) as JOB_TITLE ,max(CREATED_ON) as CREATED_ON ,max(REQUIRED_MP) as REQUIRED_MP ,max(WORK_EXPYEARS) as WORK_EXPYEARS ,
max(SALARY) as SALARY ,max(IND_ID) as IND_ID ,max(Key_skill) as Key_skill , max(STATE_ID) as STATE_ID ,max(DIST_ID) as DIST_ID,max(LOCALITY_ID) as LOCALITY_ID ,max(DEPT_ID) as DEPT_ID,2 as Priority,max(EXPIRATION_DATE) as EXPIRATION_DATE from #dummy where EXPIRATION_DATE >0 group by ej_id
) as x '
set #STRSQLNew =#STRSQLNew+' select * into #Temp2 from
(
select a.ej_id, isnull(a.JOB_TITLE,'''') as JOB_TITLE, isnull(b.ENT_NAME,'''') as ENT_NAME, CASE
WHEN DATEDIFF(SECOND, a.CREATED_ON, GETDATE()) < 60 THEN ''Just Posted''
WHEN DATEDIFF(MINUTE, a.CREATED_ON, GETDATE()) < 60 THEN CAST(DATEDIFF(MINUTE, a.CREATED_ON, GETDATE()) AS VARCHAR(10)) + '' Minutes ago''
WHEN DATEDIFF(MINUTE, a.CREATED_ON, GETDATE()) < 24 * 60 THEN CAST(FLOOR(DATEDIFF(MINUTE, a.CREATED_ON, GETDATE())/60) AS VARCHAR(10)) + '' Hours ago''
ELSE CAST(FLOOR(DATEDIFF(HOUR, a.CREATED_ON, GETDATE())/24) AS VARCHAR(10)) + ''Days ago''
END AS POSTED_ON,a.REQUIRED_MP,''1'' as Issuitable,a.job_desc, a.created_on,DATEDIFF(DAY,GETDATE(),a.EXPIRATION_DATE) as EXPIRATION_DATE
,isnull('''+#Isguest+''',''0'') as Isguest,isnull('''+#verified+''',''0'') as Isverified
,isnull(cnt,0) as Isapplied,substring(
(
Select distinct '', ''+ ST1.StateName AS [text()]
From MTB_STATESNEW ST1
Where ST1.StateId in (select items from dbo.split (a.state_id,'',''))
For XML PATH ('''')
), 2, 1000000) [StateName],
substring(
(
Select distinct '', ''+ min(convert(varchar(1000),ST1.MIN_EXP)) AS [text()]
From dbo.MTB_WORKEXP ST1
Where ST1.EXP_ID in (select items from dbo.split (a.WORK_EXPYEARS,'',''))
For XML PATH ('''')
), 2, 1000000) [min_exp],
substring(
(
Select distinct '',''+ max(convert(varchar(1000),ST1.MAX_EXP)) AS [text()]
From dbo.MTB_WORKEXP ST1
Where ST1.EXP_ID in (select items from dbo.split (a.WORK_EXPYEARS,'',''))
For XML PATH ('''')
), 2, 1000000) [max_exp],
substring(
(
Select distinct '', ''+ min(convert(varchar(1000),ST1.SR_MIN)) AS [text()]
From dbo.MTB_SALARYRANGE ST1
Where ST1.SR_ID in (select min(items) from dbo.split (a.SALARY,'',''))
For XML PATH ('''')
), 2, 1000000) [min_Salary],
substring(
(
Select distinct '',''+ max(convert(varchar(1000),ST1.sr_max)) AS [text()]
From dbo.MTB_SALARYRANGE ST1
Where ST1.SR_ID in (select items from dbo.split (a.SALARY,'',''))
For XML PATH ('''')
), 2, 1000000) [max_Salary],
substring(
(
Select distinct '',''+ (convert(varchar(1000),ST1.KEY_SKILL)) AS [text()]
From MTB_KEYSKILL ST1
Where ST1.KEYSKILL_ID in (select items from dbo.split (a.Key_skill,'',''))
For XML PATH ('''')
), 2, 1000000) [KEY_SKILL]
,
substring (
(Select distinct '',''+ (convert(varchar(1000),ST1.KEYWORDS)) AS [text()]
From mtb_keywords ST1 where st1.KEYWORD_ID in ( select items from dbo.split('''+#keyword+''','',''))
For XML PATH ('''')
), 2, 1000000) [KEY_Word],
substring (
(Select distinct '',''+ (convert(varchar(1000),ST1.DIST_NAME)) AS [text()]
From MTB_DISTSNEW ST1 where st1.DIST_ID in ( select items from dbo.split(a.DIST_ID,'',''))
For XML PATH ('''')
), 2, 1000000) [dist_name],
substring(
(select distinct '',''+(convert(varchar(1000),ST1.EQ_NAME)) as [text()]
from MTB_EDUQUALIFICATIONS ST1 where st1.EQ_ID in (select items from dbo.split(a.EQ_ID,'',''))
For XML PATH('''')
),2,1000000) [EQ_Name],
substring(
(select distinct '',''+(convert(varchar(1000),ST1.IND_NAME)) as [text()]
from mtb_industry ST1 where st1.ind_id in (select items from dbo.split(a.ind_id,'',''))
For XML PATH('''')
),2,1000000) [IND_NAME]
from #temp as a inner join MTB_ENTERPRISES as b on a.user_id = b.user_id
left join (select count (ej_id) as cnt,ej_id from TTB_JOBAPPLICATIONS where USER_ID = '''+#USER_ID+''' group by EJ_ID) as ER on ER.EJ_ID = a.EJ_ID
where( a.JOB_STATUS = 1 and a.active = 1 )
) as x'
set #STRSQLNew =#STRSQLNew+' SELECT *,isnull(min_exp,'''') +''-''+ isnull(max_exp,'''') as WORK_EXP,isnull(min_Salary,'''') +''-''+ isnull(max_salary,'''') as Salary FROM #Temp2 '
print #STRSQLNew
exec (#STRSQLNew)
select 1 as ispara1, 'Sucess' as Msg ,1 as n
end
else
begin
select top 0* from MTB_ENTERPRISES
select 0 as ispara2, 0 as n,'Some fields are Incomplete' as Msg
end
END
Error:- Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding.

What is the right way to count number of records returned by group by query

How do I count the number of actual records returned by a group by query
For e.g
-- Exec SP_GET_ITEM_STOCK 0,10,NULL,'Charger'
ALTER PROCEDURE [dbo].[SP_GET_ITEM_STOCK]
#startRowIndex int ,
#pageSize int,
#ItemID bigint = null,
#ItemName varchar(250) = null
AS
BEGIN
DECLARE #SQL varchar(MAX)
DECLARE #SQLWHERE varchar(MAX)
SET #SQL = 'WITH DATA AS (
select
ROW_NUMBER() OVER (ORDER BY Item_ID) ''SNo'',
Item_ID,
Item_Name,
SUM(Inward) as Total_Purchase,
SUM(Outward) as Total_Sale,
(sum(Inward) - sum(outward))as Balance_Stock'
Set #SQLWHERE = ' from Item_Ledger_Details where Active = 1'
IF #ItemID IS NOT NULL and #ItemID <> ''
SET #SQLWHERE = #SQLWHERE + ' and Item_ID = ' + CONVERT(varchar,#ItemID) + ''
IF #ItemName IS NOT NULL and #ItemName <> ''
SET #SQLWHERE = #SQLWHERE + ' and Item_Name like ''%' + #ItemName + '%'''
SET #SQL = #SQL + #SQLWHERE + ' group by Item_ID,Item_Name) SELECT * FROM DATA WHERE SNo BETWEEN ' + CONVERT(Varchar,#startRowIndex) + ' AND ' + CONVERT(Varchar,#startRowIndex+#pageSize) + ' ORDER BY SNo'
EXEC(#SQL +';SELECT COUNT(*) ''Count'' '+ #SQLWHERE)
print(#SQL)
END
Which returns:
I need to count the above first result records to get 1 + 1 = 2 in second result where I get count = 48
Continue Anand Answer. I've just modify his query. Below query is solved my answer. But I think may be this query needs optimization.
-- SP_GET_ITEM_STOCK 0,10,NULL,NULL
ALTER PROCEDURE [dbo].[SP_GET_ITEM_STOCK]
#startRowIndex int,
#pageSize int,
#ItemID bigint = null,
#ItemName varchar(250) = null
AS
BEGIN
Declare #Temp Table (
SNo bigint,
Item_ID bigint,
Item_Name varchar(max),
Total_Purchase money,
Total_Sale money,
Balance_Stock money
);
WITH DATA AS (
select
ROW_NUMBER() OVER (ORDER BY Item_ID) as SNo,
Item_ID,
Item_Name,
SUM(Inward) as Total_Purchase,
SUM(Outward) as Total_Sale,
(sum(Inward) - sum(outward))as Balance_Stock
from Item_Ledger_Details
where Active = 1
and (coalesce(#ItemID, '') = '' or Item_ID = CONVERT(varchar,#ItemID))
and ( coalesce(#ItemName, '') = '' or Item_Name like '%' + #ItemName + '%')
group by Item_ID,
Item_Name
)
insert into #Temp
SELECT *
FROM DATA
WHERE SNo BETWEEN #startRowIndex AND #startRowIndex+#pageSize
ORDER BY SNo
select * from #temp
SELECT COUNT(*) as Count from #temp
END
There, I've cleaned it up:
ALTER PROCEDURE [dbo].[SP_GET_ITEM_STOCK]
#startRowIndex int,
#pageSize int,
#ItemID bigint = null,
#ItemName varchar(250) = null
AS
BEGIN
;WITH DATA AS (
select
ROW_NUMBER() OVER (ORDER BY Item_ID) as SNo,
Item_ID,
Item_Name,
SUM(Inward) as Total_Purchase,
SUM(Outward) as Total_Sale,
(sum(Inward) - sum(outward))as Balance_Stock
from Item_Ledger_Details
where Active = 1
and (coalesce(#ItemID, '') = '' or Item_ID = CONVERT(varchar,#ItemID))
and ( coalesce(#ItemName, '') = '' or Item_Name like '%' + #ItemName + '%')
group by Item_ID,
Item_Name
)
SELECT *
FROM DATA
WHERE SNo BETWEEN #startRowIndex AND #startRowIndex+#pageSize
ORDER BY SNo
SELECT COUNT(*) as Count
from DATA
END

Export SQL Server info about disk, cpu and memory utilization

I am trying to use logstash to read log files. When it come to monitor SQL Server, is there anyway to export SQL Server Database Disk Usage data to a log file?
Disk usage (per database):
IF OBJECT_ID('tempdb.dbo.#space') IS NOT NULL
DROP TABLE #space
CREATE TABLE #space (
database_id INT PRIMARY KEY
, data_used_size DECIMAL(18,2)
, log_used_size DECIMAL(18,2)
)
DECLARE #SQL NVARCHAR(MAX)
SELECT #SQL = STUFF((
SELECT '
USE [' + d.name + ']
INSERT INTO #space (database_id, data_used_size, log_used_size)
SELECT
DB_ID()
, SUM(CASE WHEN [type] = 0 THEN space_used END)
, SUM(CASE WHEN [type] = 1 THEN space_used END)
FROM (
SELECT s.[type], space_used = SUM(FILEPROPERTY(s.name, ''SpaceUsed'') * 8. / 1024)
FROM sys.database_files s
GROUP BY s.[type]
) t;'
FROM sys.databases d
WHERE d.[state] = 0
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '')
EXEC sys.sp_executesql #SQL
SELECT
d.database_id
, d.name
, d.state_desc
, t.total_size
, t.data_size
, s.data_used_size
, t.log_size
, s.log_used_size
FROM (
SELECT
database_id
, log_size = CAST(SUM(CASE WHEN [type] = 1 THEN size END) * 8. / 1024 AS DECIMAL(18,2))
, data_size = CAST(SUM(CASE WHEN [type] = 0 THEN size END) * 8. / 1024 AS DECIMAL(18,2))
, total_size = CAST(SUM(size) * 8. / 1024 AS DECIMAL(18,2))
FROM sys.master_files
GROUP BY database_id
) t
JOIN sys.databases d ON d.database_id = t.database_id
LEFT JOIN #space s ON d.database_id = s.database_id
ORDER BY t.total_size DESC
Disk activity:
IF OBJECT_ID('tempdb.dbo.#tt', 'U') IS NULL
CREATE TABLE #tt (
tm DATETIME PRIMARY KEY,
total_read NUMERIC(28, 2),
total_written NUMERIC(28, 2),
total_io_count BIGINT,
total_io_wait BIGINT
)
DECLARE #current_collection_time DATETIME = GETDATE()
INSERT INTO #tt
SELECT
#current_collection_time,
SUM(num_of_bytes_read / 1024.0 / 1024.0 ),
SUM(num_of_bytes_written / 1024.0 / 1024.0 ),
SUM(num_of_reads + num_of_writes),
SUM(io_stall)
FROM sys.dm_io_virtual_file_stats(DEFAULT, DEFAULT)
DECLARE #previous_collection_time DATETIME
SELECT #previous_collection_time = tm
FROM #tt
WHERE tm < #current_collection_time
DECLARE #interval_ms INT = DATEDIFF(MILLISECOND, #previous_collection_time, #current_collection_time);
SELECT
read_mb_sec = (c.total_read - p.total_read) * 1000 / #interval_ms,
write_mp_sec = (c.total_written - p.total_written) * 1000 / #interval_ms,
response_time_ms =
CASE
WHEN (c.total_io_count - p.total_io_count) = 0
THEN 0
ELSE (c.total_io_wait - p.total_io_wait) / (c.total_io_count - p.total_io_count)
END
FROM #tt c
CROSS JOIN #tt p
WHERE c.tm = #current_collection_time
AND p.tm = #previous_collection_time
DELETE FROM #tt
WHERE tm < #current_collection_time;
Memory utilization:
DECLARE #sql_memory_mb INT
SELECT #sql_memory_mb = physical_memory_in_use_kb / 1024
FROM sys.dm_os_process_memory
SELECT
total_memory_mb = total_physical_memory_kb / 1024,
memory_in_use_mb = (total_physical_memory_kb - available_physical_memory_kb) / 1024,
sql_memory_mb = #sql_memory_mb
FROM sys.dm_os_sys_memory
CPU utilization:
SELECT
cpu_total =
CASE WHEN cpu_sql > cpu_total AND cpu_sql <= 99.
THEN cpu_sql
ELSE cpu_total
END,
cpu_sql
FROM (
SELECT cpu_total = 100 - x.value('(./Record/SchedulerMonitorEvent/SystemHealth/SystemIdle/text())[1]', 'TINYINT')
FROM (
SELECT TOP(1) [timestamp], x = CONVERT(XML, record)
FROM sys.dm_os_ring_buffers
WHERE ring_buffer_type = N'RING_BUFFER_SCHEDULER_MONITOR'
AND record LIKE '%<SystemHealth>%'
) t
) x
CROSS JOIN (
SELECT
cpu_sql = (
MAX(CASE WHEN counter_name = 'CPU usage %' THEN t.cntr_value * 1. END) /
MAX(CASE WHEN counter_name = 'CPU usage % base' THEN t.cntr_value END)
) * 100
FROM (
SELECT TOP(2) cntr_value, counter_name
FROM sys.dm_os_performance_counters
WHERE counter_name IN ('CPU usage %', 'CPU usage % base')
AND instance_name = 'default'
) t
) t
This queries you can run from jobs and put required information into tables.
How to load data into file:
/*
EXEC sys.sp_configure 'show advanced options', 1
GO
RECONFIGURE
GO
EXEC sys.sp_configure 'xp_cmdshell', 1
GO
RECONFIGURE WITH OVERRIDE
GO
*/
DECLARE #sql NVARCHAR(4000) = 'bcp "SELECT * FROM dbo.disk_activity" queryout "D:\sample.html" -S ' + ##servername + ' -T -w -r -t'
EXEC sys.xp_cmdshell #sql

Invalid column name '#Results'

alter PROCEDURE sp_Get_CustInfoSerach2
(#PageIndex INT = 1
,#PageSize INT = 10
,#RecordCount INT OUTPUT
,#ColumnName VARCHAR(50)=null
,#Value VARCHAR(50)=null
,#ddlValue VARCHAR(50)=null
,#txtValue VARCHAR(50)=null
,#status varchar(30))
AS
BEGIN
SET NOCOUNT ON;
DECLARE #cmd AS NVARCHAR(max)
if #txtValue IS NULL
Begin
SET #Value = ''''+#ddlValue+ ''''
End
else if #ddlValue IS NULL
begin
SET #Value = ''''+#txtValue+ ''''
end
SET #cmd = 'SELECT ROW_NUMBER() OVER
(
ORDER BY C_Register.UserId desc
)AS RowNumber
,C_Register.UserId, C_Register.Name, C_Register.UserName, C_Register.Status,
Packages.PackagePeriod, Packages.PackageName, C_Register.ActivationDate,
Receive_Payment.OldExpiryDate, Receive_Payment.Balance, Receive_Payment.PyingAmount,
Receive_Payment.LastPaidDate, C_Register.LastUpdateTime,
Area.AreaName, C_Register.MobNo, Employee.EmpName, C_Register.Address,C_Register.CreatedDate
INTO'+ #Results+'
FROM C_Register INNER JOIN Receive_Payment ON C_Register.UserId = Receive_Payment.UserId
INNER JOIN Area ON C_Register.AreaId = Area.AreaId
INNER JOIN Employee ON Receive_Payment.EmpId = Employee.EmpId
INNER JOIN Packages ON Receive_Payment.PackageId = Packages.PackageId
where C_Register.AccountExpiry= Receive_Payment.OldExpiryDate And C_Register.Status = '+#status+'And
' + #ColumnName + ' = ' + #Value
SELECT #RecordCount = COUNT(*)
FROM #Results
SELECT * FROM #Results
WHERE RowNumber BETWEEN(#PageIndex -1) * #PageSize + 1 AND(((#PageIndex -1) * #PageSize + 1) + #PageSize) - 1
DROP TABLE #Results
EXEC(#cmd)
END
throwing error:
Invalid column name '#Results'.
how to solve it?
If i understand your problem correctly you should first exec dynamic sql before select from temporary table
Alter PROCEDURE sp_Get_CustInfoSerach2
(
#PageIndex INT = 1 ,
#PageSize INT = 10 ,
#RecordCount INT OUTPUT ,
#ColumnName VARCHAR(50)=null ,
#Value VARCHAR(50)=null ,
#ddlValue VARCHAR(50)=null ,
#txtValue VARCHAR(50)=null ,
#status varchar(30)
)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #cmd AS NVARCHAR(max)
If #txtValue IS NULL
Begin
SET #Value = ''''+#ddlValue+ ''''
End
Else
if #ddlValue IS NULL
Begin
SET #Value = ''''+#txtValue+ ''''
End
SET #cmd = 'SELECT ROW_NUMBER() OVER ( ORDER BY C_Register.UserId desc )AS RowNumber,
C_Register.UserId, C_Register.Name, C_Register.UserName, C_Register.Status,
Packages.PackagePeriod, Packages.PackageName, C_Register.ActivationDate,
Receive_Payment.OldExpiryDate, Receive_Payment.Balance, Receive_Payment.PyingAmount,
Receive_Payment.LastPaidDate, C_Register.LastUpdateTime,
Area.AreaName, C_Register.MobNo, Employee.EmpName, C_Register.Address,C_Register.CreatedDate
INTO #Results
FROM C_Register INNER JOIN Receive_Payment ON C_Register.UserId = Receive_Payment.UserId
INNER JOIN Area ON C_Register.AreaId = Area.AreaId
INNER JOIN Employee ON Receive_Payment.EmpId = Employee.EmpId
INNER JOIN Packages ON Receive_Payment.PackageId = Packages.PackageId
where C_Register.AccountExpiry= Receive_Payment.OldExpiryDate And C_Register.Status = '+#status+'And
' + #ColumnName + ' = ' + #Value
/*First Execute above dynamic Sql query */
EXEC(#cmd)
/* From the above execute statemnet the query will executed and temporary table will created on the fly */
SELECT #RecordCount = COUNT(*)
FROM #Results
SELECT * FROM #Results
WHERE RowNumber BETWEEN(#PageIndex -1) * #PageSize + 1 AND(((#PageIndex -1) * #PageSize + 1) + #PageSize) - 1
DROP TABLE #Results
Problem in your query is creation of temp table thats not right way to create temp table inside dynamic query.
But even if you create temp table inside a dynamic query it can be accessed only inside the session of dynamic query. If you try to select the temp outside of dynamic query which is created inside the dynamic query you will get a error saying object doesnot exist.
Since you know the number of columns present in the result of dynamic query you can create the temp table outside of dynamic query and insert the records through dynamic query.
Try changing your procedure like this.
ALTER PROCEDURE Sp_get_custinfoserach2 (#PageIndex INT = 1,
#PageSize INT = 10,
#RecordCount INT output,
#ColumnName VARCHAR(50)=NULL,
#Value VARCHAR(50)=NULL,
#ddlValue VARCHAR(50)=NULL,
#txtValue VARCHAR(50)=NULL,
#status VARCHAR(30))
AS
BEGIN
SET nocount ON;
DECLARE #cmd AS NVARCHAR(max)
IF #txtValue IS NULL
BEGIN
SET #Value = '''' + #ddlValue + ''''
END
ELSE IF #ddlValue IS NULL
BEGIN
SET #Value = '''' + #txtValue + ''''
END
/*create a temp as same structure of your dynamic query select statement*/
CREATE TABLE #result
(
rownum INT,
userid INT,
NAME VARCHAR(100),
username VARCHAR(100),
status VARCHAR(15),
packageperiod VARCHAR(15),
packagename VARCHAR(100),
activationdate DATETIME,
oldexpirydate DATETIME,
balance NUMERIC(22, 4),
pyingamount NUMERIC(22, 4),
lastpaiddate DATETIME,
lastupdatetime DATETIME,
areaname VARCHAR(100),
mobno INT,
empname VARCHAR(100),
address VARCHAR(5000),
createddate DATETIME
)
SET #cmd =
' Insert into #result
SELECT ROW_NUMBER() OVER (ORDER BY C_Register.UserId desc )AS RowNumber,
C_Register.UserId, C_Register.Name, C_Register.UserName,
C_Register.Status, Packages.PackagePeriod, Packages.PackageName,
C_Register.ActivationDate,Receive_Payment.OldExpiryDate,
Receive_Payment.Balance, Receive_Payment.PyingAmount,
Receive_Payment.LastPaidDate, C_Register.LastUpdateTime,
Area.AreaName, C_Register.MobNo, Employee.EmpName,
C_Register.Address,C_Register.CreatedDate
FROM C_Register
INNER JOIN Receive_Payment
ON C_Register.UserId = Receive_Payment.UserId
INNER JOIN Area
ON C_Register.AreaId = Area.AreaId
INNER JOIN Employee
ON Receive_Payment.EmpId = Employee.EmpId
INNER JOIN Packages
ON Receive_Payment.PackageId = Packages.PackageId
where C_Register.AccountExpiry= Receive_Payment.OldExpiryDate And C_Register.Status = ' + #status + ' And ' + #ColumnName + ' = ' + #Value
SELECT #RecordCount = Count(*)
FROM #results
SELECT *
FROM #results
WHERE rownumber BETWEEN( #PageIndex - 1 ) * #PageSize + 1 AND( (
( #PageIndex - 1 ) * #PageSize + 1 ) +
#PageSize ) - 1
DROP TABLE #results
EXEC(#cmd)
END
Note : I have given generic datatypes to temp table columns please change the datetypes according to your schema.

Is there a SQL Server Utility that generates a big list of all Server Logins and an overview of their access?

I would like to know if there is a utility out there that can list the Server Logins on a particular server and their access.
This would be the information I get from right clicking each user -> Properties -> User Mapping
but instead of manually going through that process for each user, it just lists the information.
For example:
MyDomain\John
- Server Roles
- sysadmin
- MyDatabase1
- Roles
db_reader
public
- MyDatabase2
- Roles
db_reader
public
MyDomain\Steve
- MyDatabase1
- Roles
db_reader
public
I hacked up the sp_helplogins system stored procedure to return close to what you're looking for.
I can't get the script to paste correctly so here is a link to the script.
DECLARE #LoginNamePattern sysname = NULL
set nocount on
declare
#exec_stmt nvarchar(3550)
declare
#CountSkipPossUsers int
,#Int1 int
declare
#c10DBName sysname
,#c10DBStatus int
,#c10DBSID varbinary(85)
declare
#charMaxLenLoginName varchar(11)
,#charMaxLenDBName varchar(11)
,#charMaxLenUserName varchar(11)
declare
#DBOptLoading int --0x0020 32 "DoNotRecover"
,#DBOptPreRecovery int --0x0040 64
,#DBOptRecovering int --0x0080 128
,#DBOptSuspect int --0x0100 256 ("not recovered")
,#DBOptOffline int --0x0200 512
,#DBOptDBOUseOnly int --0x0800 2048
,#DBOptSingleUser int --0x1000 4096
------------- create work holding tables ----------------
-- Create temp tables before any DML to ensure dynamic
CREATE TABLE #tb1_UA
(
LoginName sysname collate database_default NOT Null
,DBName sysname collate database_default NOT Null
,UserName sysname collate database_default NOT Null
)
--------------- Cursor, for DBNames -------------------
declare ms_crs_10_DB
Cursor local static For
select
name ,status ,sid
from
master.dbo.sysdatabases
OPEN ms_crs_10_DB
----------------- LOOP 10: thru Databases ------------------
WHILE (10 = 10)
begin --LOOP 10: thru Databases
FETCH
next
from
ms_crs_10_DB
into
#c10DBName
,#c10DBStatus
,#c10DBSID
IF (##fetch_status <> 0)
begin
deallocate ms_crs_10_DB
BREAK
end
-------------------- Okay if we peek inside this DB now?
IF ( #c10DBStatus & #DBOptDBOUseOnly > 0
AND #c10DBSID <> suser_sid()
)
begin
select #CountSkipPossUsers = #CountSkipPossUsers + 1
CONTINUE
end
IF (#c10DBStatus & #DBOptSingleUser > 0)
begin
select #Int1 = count(*)
from sys.dm_exec_requests
where session_id <> ##spid
and database_id = db_id(#c10DBName)
IF (#Int1 > 0)
begin
select #CountSkipPossUsers = #CountSkipPossUsers + 1
CONTINUE
end
end
IF (#c10DBStatus &
(
#DBOptLoading
| #DBOptRecovering
| #DBOptSuspect
| #DBOptPreRecovery
)
> 0
)
begin
select #CountSkipPossUsers = #CountSkipPossUsers + 1
CONTINUE
end
IF (#c10DBStatus &
(
#DBOptOffline
)
> 0
)
begin
--select #CountSkipPossUsers = #CountSkipPossUsers + 1
CONTINUE
end
IF (has_dbaccess(#c10DBName) <> 1)
begin
raiserror(15622,-1,-1, #c10DBName)
CONTINUE
end
--------------------- Add the User info to holding table.
select #exec_stmt = '
INSERT #tb1_UA
(
DBName
,LoginName
,UserName
)
select
N' + quotename(#c10DBName, '''') + '
,l.name
,u2.name
from
' + quotename(#c10DBName, '[')+ '.sys.database_role_members m
,' + quotename(#c10DBName, '[')+ '.sys.database_principals u1
,' + quotename(#c10DBName, '[')+ '.sys.database_principals u2
,sys.server_principals l
where
u1.sid = l.sid
and m.member_principal_id = u1.principal_id
and m.role_principal_id = u2.principal_id' +
case
when #LoginNamePattern is null
then ''
else ' and ( l.name = N' + quotename(#LoginNamePattern , '''') + '
or l.name = N' + quotename(#LoginNamePattern , '''') + ')'
end
EXECUTE(#exec_stmt)
end --loop 10
------------ Optimize UA report column display widths -----------
select
#charMaxLenLoginName =
convert ( varchar
,isnull ( max(datalength(LoginName)) ,9)
)
,#charMaxLenDBName =
convert ( varchar
,isnull ( max(datalength(DBName)) ,6)
)
,#charMaxLenUserName =
convert ( varchar
,isnull ( max(datalength(UserName)) ,8)
)
from
#tb1_UA
------------ Print out the UserOrAlias report ------------
EXEC(
'
set nocount off
select
''LoginName'' = substring (LoginName ,1 ,'
+ #charMaxLenLoginName + ')
,''DBName'' = substring (DBName ,1 ,'
+ #charMaxLenDBName + ')
,''MemberOf'' = substring (UserName ,1 ,'
+ #charMaxLenUserName + ')
from
#tb1_UA
order by
1 ,2 ,3
Set nocount on
'
)
DROP Table #tb1_UA

Resources