Logs of executed Query in SQL Server - sql

Database having 5 users
All users are running queries on database
we need to find what are the things all users doing like (Query , session_id,starttime , endtime,Database name,username , hostname )
we need to insert all the data into one table.

SELECT sdest.DatabaseName
,sdes.session_id
,sdes.[host_name]
,sdes.[program_name]
,sdes.client_interface_name
,sdes.login_name
,sdes.login_time
,sdes.nt_domain
,sdes.nt_user_name
,sdec.client_net_address
,sdec.local_net_address
,sdest.ObjName
,sdest.Query
FROM sys.dm_exec_sessions AS sdes
INNER JOIN sys.dm_exec_connections AS sdec ON sdec.session_id = sdes.session_id
CROSS APPLY (
SELECT db_name(dbid) AS DatabaseName
,object_id(objectid) AS ObjName
,ISNULL((
SELECT TEXT AS [processing-instruction(definition)]
FROM sys.dm_exec_sql_text(sdec.most_recent_sql_handle)
FOR XML PATH('')
,TYPE
), '') AS Query
FROM sys.dm_exec_sql_text(sdec.most_recent_sql_handle)
) sdest
where sdes.session_id <> ##SPID
--and sdes.nt_user_name = '' -- Put the username here !
ORDER BY sdec.session_id

Related

Getting the user name who executed the stored procedure in Database?

Someone ran a stored procedure from his machine, and I just want to know who executed that stored procedure.
I am trying to see sys.dm_exec_procedure_stats but I'm having no luck:
SELECT object_id
FROM sys.dm_exec_procedure_stats
WHERE OBJECT_NAME(object_id,database_id) = 'SpName'
I have used https://dba.stackexchange.com/questions/135078/how-to-get-history-of-queries-executed-with-username-in-sql and updated with my logic and its worked for me
USE master
go
SELECT top 10 sdest.DatabaseName
,sdes.session_id
,sdes.[host_name]
,sdes.[program_name]
,sdes.client_interface_name
,sdes.login_name
,sdes.login_time
,sdes.nt_domain
,sdes.nt_user_name
,sdec.client_net_address
,sdec.local_net_address
,sdest.ObjName
,sdest.Query
FROM sys.dm_exec_sessions AS sdes
INNER JOIN sys.dm_exec_connections AS sdec ON sdec.session_id = sdes.session_id
CROSS APPLY (
SELECT db_name(dbid) AS DatabaseName
,object_id(objectid) AS ObjName
,ISNULL((
SELECT TEXT AS [processing-instruction(definition)]
FROM sys.dm_exec_sql_text(sdec.most_recent_sql_handle)
FOR XML PATH('')
,TYPE
), '') AS Query
FROM sys.dm_exec_sql_text(sdec.most_recent_sql_handle) WHERE OBJECT_NAME(objectid,dbid)='MySp'
) sdest
where sdes.session_id <> ##SPID
--and sdes.nt_user_name = '' -- Put the username here !
ORDER BY sdec.session_id

How to Group data based on Process type in SQL Server? [duplicate]

This question already has answers here:
Simulating group_concat MySQL function in Microsoft SQL Server 2005?
(12 answers)
Closed 6 years ago.
I know that in sql server we cannot use Group_concat function but here is one issue i have in which i need to Group_Concat my query.I google it found some logic but not able to correct it.My sql query is
select m.maskid,m.maskname,m.schoolid,s.schoolname,
md.maskdetail
from tblmask m join school s on s.id = m.schoolid
join maskdetails md on m.maskid = md.maskid
order by m.maskname ;
It gives me result like
Just look first 3 rows In that maskid,maskname,schoolid,schoolname is same but maskdetail is different so want to one row for that in which last column can contain all maskdetails as per maskid and so on.
I want my output like
And so on.So please help me while making a query for that.
Thanks in advance.
Query:
SELECT
m.maskid
, m.maskname
, m.schoolid
, s.schoolname
, maskdetail = STUFF((
SELECT ',' + md.maskdetail
FROM dbo.maskdetails md
WHERE m.maskid = md.maskid
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
FROM dbo.tblmask m
JOIN dbo.school s ON s.ID = m.schoolid
ORDER BY m.maskname
Additional information:
String Aggregation in the World of SQL Server
Select
A.maskid
, A.maskname
, A.schoolid
, B.schoolname
, STUFF((
SELECT ',' + T.maskdetail
FROM dbo.maskdetails T
WHERE A.maskid = T.maskid
FOR XML PATH('')), 1, 1, '') as maskdetail
FROM dbo.tblmask A
JOIN dbo.school B ON B.ID = A.schoolid
Group by A.maskid
, A.maskname
, A.schoolid
, B.schoolname
This can also be achieved using the Scalar-Valued Function in MSSQL 2008
Declare your function as following,
CREATE FUNCTION [dbo].[FunctionName]
(#MaskId INT)
RETURNS Varchar(500)
AS
BEGIN
DECLARE #SchoolName varchar(500)
SELECT #SchoolName =ISNULL(#SchoolName ,'')+ MD.maskdetail +', '
FROM maskdetails MD WITH (NOLOCK)
AND MD.MaskId=#MaskId
RETURN #SchoolName
END
And then your final query will be like
SELECT m.maskid,m.maskname,m.schoolid,s.schoolname,
(SELECT [dbo].[FunctionName](m.maskid)) 'maskdetail'
FROM tblmask m JOIN school s on s.id = m.schoolid
ORDER BY m.maskname ;
Note: You may have to change the function, as I don't know the complete table structure.
Please run the below query, it doesn't requires STUFF and GROUP BY in your case:
Select
A.maskid
, A.maskname
, A.schoolid
, B.schoolname
, CAST((
SELECT T.maskdetail+','
FROM dbo.maskdetails T
WHERE A.maskid = T.maskid
FOR XML PATH(''))as varchar(max)) as maskdetail
FROM dbo.tblmask A
JOIN dbo.school B ON B.ID = A.schoolid

How to merge multiple (single column) rows into single string in SQL SERVER [duplicate]

This question already has answers here:
Simulating group_concat MySQL function in Microsoft SQL Server 2005?
(12 answers)
Closed 6 years ago.
I know that in sql server we cannot use Group_concat function but here is one issue i have in which i need to Group_Concat my query.I google it found some logic but not able to correct it.My sql query is
select m.maskid,m.maskname,m.schoolid,s.schoolname,
md.maskdetail
from tblmask m join school s on s.id = m.schoolid
join maskdetails md on m.maskid = md.maskid
order by m.maskname ;
It gives me result like
Just look first 3 rows In that maskid,maskname,schoolid,schoolname is same but maskdetail is different so want to one row for that in which last column can contain all maskdetails as per maskid and so on.
I want my output like
And so on.So please help me while making a query for that.
Thanks in advance.
Query:
SELECT
m.maskid
, m.maskname
, m.schoolid
, s.schoolname
, maskdetail = STUFF((
SELECT ',' + md.maskdetail
FROM dbo.maskdetails md
WHERE m.maskid = md.maskid
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
FROM dbo.tblmask m
JOIN dbo.school s ON s.ID = m.schoolid
ORDER BY m.maskname
Additional information:
String Aggregation in the World of SQL Server
Select
A.maskid
, A.maskname
, A.schoolid
, B.schoolname
, STUFF((
SELECT ',' + T.maskdetail
FROM dbo.maskdetails T
WHERE A.maskid = T.maskid
FOR XML PATH('')), 1, 1, '') as maskdetail
FROM dbo.tblmask A
JOIN dbo.school B ON B.ID = A.schoolid
Group by A.maskid
, A.maskname
, A.schoolid
, B.schoolname
This can also be achieved using the Scalar-Valued Function in MSSQL 2008
Declare your function as following,
CREATE FUNCTION [dbo].[FunctionName]
(#MaskId INT)
RETURNS Varchar(500)
AS
BEGIN
DECLARE #SchoolName varchar(500)
SELECT #SchoolName =ISNULL(#SchoolName ,'')+ MD.maskdetail +', '
FROM maskdetails MD WITH (NOLOCK)
AND MD.MaskId=#MaskId
RETURN #SchoolName
END
And then your final query will be like
SELECT m.maskid,m.maskname,m.schoolid,s.schoolname,
(SELECT [dbo].[FunctionName](m.maskid)) 'maskdetail'
FROM tblmask m JOIN school s on s.id = m.schoolid
ORDER BY m.maskname ;
Note: You may have to change the function, as I don't know the complete table structure.
Please run the below query, it doesn't requires STUFF and GROUP BY in your case:
Select
A.maskid
, A.maskname
, A.schoolid
, B.schoolname
, CAST((
SELECT T.maskdetail+','
FROM dbo.maskdetails T
WHERE A.maskid = T.maskid
FOR XML PATH(''))as varchar(max)) as maskdetail
FROM dbo.tblmask A
JOIN dbo.school B ON B.ID = A.schoolid

Tsql queries into XML using a format

I've never used XML before. I have the following queries - that need to be output into XML file in a particular format
---- Show Server details
GO
SELECT
##servername as ServerName,
##version as Environment,
SERVERPROPERTY('productversion'),
SERVERPROPERTY ('InstanceName')
-- Show DB details
SELECT
name AS DBName ,
Collation_name as Collation,
User_access_Desc as UserAccess,
Compatibility_level AS CompatiblityLevel ,
state_desc as Status,
Recovery_model_desc as RecoveryModel
FROM sys.databases
ORDER BY Name
-- Sysadmin Roles
SELECT
p.name AS [Name],
r.type_desc,
r.is_disabled,
r.default_database_name
FROM
sys.server_principals r
INNER JOIN
sys.server_role_members m ON r.principal_id = m.role_principal_id
INNER JOIN
sys.server_principals p ON p.principal_id = m.member_principal_id
WHERE
r.type = 'R' and r.name = N'sysadmin'
-- Find all users associated with a database
DECLARE #DB_USers TABLE
(DBName sysname, UserName varchar(max), LoginType sysname, AssociatedRole varchar(max))--,create_date datetime,modify_date datetime)
INSERT #DB_USers
EXEC sp_MSforeachdb
use [?]
SELECT ''?'' AS DB_Name,
case prin.name when ''dbo'' then prin.name + '' (''+ (select SUSER_SNAME(owner_sid) from master.sys.databases where name =''?'') + '')'' else prin.name end AS UserName,
prin.type_desc AS LoginType,
isnull(USER_NAME(mem.role_principal_id),'''') AS AssociatedRole
FROM sys.database_principals prin
LEFT OUTER JOIN sys.database_role_members mem ON prin.principal_id=mem.member_principal_id
WHERE prin.sid IS NOT NULL and prin.sid NOT IN (0x00) and
prin.is_fixed_role <> 1 AND prin.name NOT LIKE ''##%'''
SELECT
DBName,UserName ,LoginType ,
STUFF(
(
SELECT ',' + CONVERT(VARCHAR(500), AssociatedRole)
FROM #DB_USers user2
WHERE
user1.DBName=user2.DBName AND user1.UserName=user2.UserName
FOR XML PATH('')
)
,1,1,'') AS Permissions_user
FROM #DB_USers user1
GROUP BY
DBName,UserName ,LoginType --,create_date ,modify_date
ORDER BY DBName,UserName
--List of all the jobs currently running on server
SELECT
job.job_id,
notify_level_email,
name,
enabled,
description,
step_name,
command,
server,
database_name
FROM
msdb.dbo.sysjobs job
INNER JOIN
msdb.dbo.sysjobsteps steps
ON
job.job_id = steps.job_id
-- Show details of extended stored procedures
SELECT * FROM master.sys.extended_procedures
I don't know where to start

Mysql query : If value(s) exist(s) in column, select just the value(s), else select all

Having a Mysql database, I have to select all ( TUser.Name, TAccount.Name ) pairs if TUser.name not exists in variable #UserNames.
If exists, I have to select only the ( TUser.Name, TAccount.Name ) pairs where TUser.name in #UserNames.
Something like the last line of the below query :
DECLARE #UserNames = "Alpha, Beta, Gama";
SELECT User.Name
, Account.Name
FROM TUser
, TAccount
, TUserAccount
WHERE TAccount.ID = TUserAccount.AccountID
AND TUserAccount.UserID = User.ID
-- please rewrite this line
AND TUser.Name IN ( IFNULL ( ( SELECT ID FROM TUser WHERE Name IN #UserNames ) , ( SELECT ID FROM TUser ) ) )
Thank you in advance !
You can't return mutually exclusive result sets with your criteria, without using a IF statement:
SELECT #sum := SUM(FIND_IN_SET(u.name, #UserNames))
FROM TUSER u
IF #sum > 0 THEN
SELECT u.name,
a.name
FROM TUSER u
JOIN TUSERACCOUNT ua ON ua.userid = u.id
JOIN TACCOUNT a ON a.id = ua.accountid
WHERE FIND_IN_SET(u.name, #UserNames) > 0
ELSE
SELECT u.name,
a.name
FROM TUSER u
JOIN TUSERACCOUNT ua ON ua.userid = u.id
JOIN TACCOUNT a ON a.id = ua.accountid
END IF;
You could make that work as a PreparedStatement, MySQL's dynamic SQL, but you still need to run a query to know if you need to return all or a subset.
References:
FIND_IN_SET
IF statements
SELECT
User.Name,
Account.Name
FROM TUser
JOIN TAccount
ON TAccount.Name = TUser.Name
JOIN TUserAccount
ON TUserAccount.AccountID = TAccount.ID
AND TUserAccount.UserID = TUser.ID
LEFT JOIN (
SELECT ID FROM TUser WHERE Name IN #UserNames
) AS UsersFound
ON TUser.ID = UsersFound.ID
Something like that? I haven't tested it though.
Ok, so this is what I would call 'hacks' rather than normall database querying, and I would disrecommend getting in the position you have to deal with in the first place. The right way to deal with a list of items like this is to have your application language parse it into a nice list you can use to build a normal, regular SQL IN list, like so:
TUser.Name IN ('Name1', 'Name2',...., 'NameX')
But anyway, if you want to stick to the original problem and your database is mysql, you can do it in a remotely sane way in a single query like this:
SET #UserNames := 'Alpha,Beta,Gama';
SELECT TUser.Name
, TAccount.Name
FROM TUser
INNER JOIN TUserAccount
ON TUser.ID = TUserAccount.UserID
INNER JOIN TAccount
ON TUserAccount.AccountID = TAccount.ID
WHERE FIND_IN_SET(TUser.Name, #UserNames)
OR (SELECT COUNT(*)
FROM TUser.Name
WHERE FIND_IN_SET(TUser.Name, #UserNames)) = 0
Note that I did change the input data somewhat - I don't have any spaces behind the commas. If that is unacceptable, simply change each occurrence of #UserNames in the query with REPLACE(#UserNames, ', ', ','). Also please note that it's performance down the drain as it is impossible to use any indexes on TUser.Name to filter for specific users.
I already mentioned that you really should make a proper IN list of your data. And you can do so directly in SQL too (dynamic SQL):
SET #UserNames := 'Alpha, Beta, Gama';
SET #stmt := CONCAT(
' SELECT TUser.Name'
,' , TAccount.Name'
,' FROM TUser'
,' INNER JOIN TUserAccount'
,' ON TUser.ID = TUserAccount.UserID'
,' INNER JOIN TAccount'
,' ON TUserAccount.AccountID = TAccount.ID'
,' WHERE TUser.Name IN (''', REPLACE(#UserNames, ', ', ''',''') , ''')'
,' OR (SELECT COUNT(*) '
,' FROM TUser.Name'
,' WHERE TUser.Name IN (''', REPLACE(#UserNames, ', ', ''',''') , ''')) = 0'
)
PREPARE stmt FROM #stmt;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
(Note that in this case, I could use the user name list with spaces unaltered)