I am trying to track SQL logins successes and failures and store them in a SQL table for querying purposes. I have written a query that works, but my problem is, when the login name contains the domain, it works fine, but if it does not contain a domain, it addess extra text. I was hoping someone could help me review my code and see how to remove the extra after the login name.
Example of what it returns:
Domain\BBruning
Domain\SQLServ
Domain\BSmith
Domain\JHarris’.
scgWeb’. Reason: F
cpadmin’. Reason:
CREATE TABLE [dbo].[#TmpErrorLog]
([LogDate] DATETIME NULL,
[ProcessInfo] VARCHAR(20) NULL,
[Text] VARCHAR(MAX) NULL);
CREATE TABLE [dbo].[#TmpErrorLog2]
([LogDate] DATETIME NULL,
[ProcessInfo] VARCHAR(20) NULL,
[Text] VARCHAR(MAX) NULL,
[LoginAttempt] VARCHAR(20) NULL,
[ServerName] VARCHAR(20) NULL);
INSERT INTO #TmpErrorLog ([LogDate], [ProcessInfo], [Text])
EXEC [master].[dbo].[xp_readerrorlog] 0 ;
INSERT INTO #TmpErrorLog2 ([LogDate], [ProcessInfo], [Text], [LoginAttempt])
Select LogDate, ProcessInfo, Text, SUBSTRING(Text,0,16) as LoginAttempt
From #TmpErrorLog
Where LogDate > GETDATE() - 120 and
[ProcessInfo] = 'Logon' and
Text like '%Login%' and text not like '%untrusted%'
INSERT INTO [MyTABLE] ([LogDate], [LoginAttempt], [LoginUser], [ServerName], [Log_date_key])
Select
LogDate,
Case LoginAttempt When 'Login succeeded' Then 'Successful' ELSE 'Failed' End as LoginAttempt,
SUBSTRING(SUBSTRING(Text, CHARINDEX('''', Text,1), CHARINDEX('''', Text, 0) - 4),2,50) as LoginUser, @@SERVERNAME, (Convert(INT, LogDate, 112))
From #TmpErrorLog2
Where LogDate Not In(Select LogDate From [MyTable])
Drop Table #TmpErrorLog
Drop Table #TmpErrorLog2
Your substring usage is a little off in the final select.
You have
where what you need is
You were providing a start location and an end location, tsql requires the starting location and the length of string you wish returned.