Last modification Date file system by creating a script - sql

I need to create an script or query to give me the last modification date of a file system. I have the below query and it works perfectly for an overwitted backup file. but I need to run it for *.bak that shows me the latest backup file modification date during many backup files:
--
if exists(select 1 from tempdb..sysobjects where name='##tmp')
drop table ##tmp
create table ##tmp(mdate varchar(8000))
insert ##tmp
exec master.dbo.xp_cmdshell 'dir g:\SQL_Backup\filename.bak' -- (I need the --last backup file name which the name keep changing every week)
set rowcount 5
delete from ##tmp
set rowcount 0
select top(1) substring(mdate,1,20) as 'Last modified date' from ##tmp

I've never worked with these views, so this really need a reality check before you really integrate it, but this may help:
select
top 1 backupSetName = bs.name,
backupFilePath = bf.physical_name,
backupFileLogicalName = bf.logical_name,
bs.backup_start_date,
bs.backup_finish_date
from msdb.dbo.backupfile bf
join msdb.dbo.backupSet bs on bf.backup_set_id = bs.backup_set_id
where right(bf.physical_name,4) = '.mdf'
order by backup_finish_date desc;
"Backup Set" records the actual dates. Since it is one-to-many with "Backup Files", it means that the '.mdf' and '.ldf' file dates are recorded together. I just excluded the latter in the above output.

I can run the PowerShell script and store in in sql server job. It ran successfully.
$source = "\00.0.00.00\your file location"
$filetype = "dif" (or "bak")
Get-ChildItem "$source*" -Include "*.$filetype" | sort LastWriteTime | select -last 1
$datetime=[datetime]::Today
if($datetime.DayOfWeek -match 'Monday'){
Write-Host "YES"
}elseif($datetime.DayOfWeek -match 'Tuesday|Thursday|Saturday'){
Write-Host "NO"
}else{
Write-Host "YES"
}

Related

weekly event select into file with different filenames depending on the variables(MariaDB)

I've always been a silent reader here until now.
Now I would like to ask for your expertise and post my ver first question here.
I have to achieve the following task on a weekly basis in my MariaDB via Events:
Every Week on Saturday night at midnight, i want to save the results of a certain view in an excel file (xlsx). The filename should be variable depending on the site_id and the current timestamp.
After saving the results into the file I want to cleanup the DB Tables with another Event, but the previous event must be successfully finished as a condition to start the cleanup event.
e.g.filename:
viewname_[site_id]_timestamp.xlsx
overall_weekly _3_01082022.xlsx
This is what I have so far:
EVENT 1(saving results into file):
CREATE EVENT overall_weekly
ON SCHEDULE EVERY 1 WEEK
STARTS TRUNCATE(CURRENT_TIMESTAMP) + '00:00:00' HOUR_SECONDS
ON COMPLETION PRESERVE
ENABLE
DO
DECLARE #path = char
DECLARE #view = char
DECLARE #site_id = int(3)
DECLARE #timestamp = timestamp
DECLARE #filetype = char(5)
DECLARE #full_filename = char
SET #path = "/home/reports/"
SET #view = "overall_traffic_weekly"
SET #site_id = 3
SET #timestamp = current_timestamp
SET #filetype = ".xlsx"
SET #full_filename = CONCAT(#path,#view,#site_id,#timestamp,#filetype)
SELECT * FROM
(
SELECT 'Column_name_1','Column_name2', ...
UNION ALL
(
SELECT * FROM overall_weekly
WHERE site_id = 3
)
) resulting_set
INTO OUTFILE #full_filename
FIELDS TERMINATED BY ';'
OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '/n';
EVENT 2(cleanup):
EVENT 1 must be SUCCESSFULLY finished for event 2 to start.
IF event 1 finishes with errors, cleanup must not start.
CREATE EVENT cleanup
ON SCHEDULE EVERY 1 WEEK
STARTS TRUNCATE(CURRENT_TIMESTAMP) + '03:00:00' HOUR_SECONDS
ON COMPLETION PRESERVE
ENABLE
DO
TRUNCATE sourcetable1,
TRUNCATE Sourcetable2
;
Many thanks for reading.
Problem solved:
I used 2 tables instead and matched the 2 records together in a third table

How Do I Save SQL Server Backup with Date Filename

Hi can I convert the following code so that the backup includes the date and time in the filename.
USE SysproCompany
GO
EXEC('BACKUP DATABASE [Company] TO DISK = N''G:\SQLBackups\INSTANCE1\MonthEndBackup\Company\MonthEndBackup.bak'' WITH NOFORMAT, COPY_ONLY,INIT,
NAME = N''MonthEndBackup'', SKIP, NOREWIND, NOUNLOAD, STATS = 10
')
PRINT 'Backup of Syspro Company started'
GO
PRINT 'Backup of Syspro Company complete'
You don't need exec to begin with. Just execute
BACKUP DATABASE [Company]
TO DISK = N''G:\SQLBackups\INSTANCE1\MonthEndBackup\Company\MonthEndBackup.bak''
WITH NOFORMAT, COPY_ONLY,INIT,
NAME = N''MonthEndBackup'', SKIP, NOREWIND, NOUNLOAD, STATS = 10
You'll have to specify the file name yourself, paths don't use formatting characters or patterns. After all, different DBAs use completely different folder and naming conventions. You can calculate the name in a variable before you use it.
A far better option though, the one used by most DBAs, is to use Ola Hallengren's backup scripts to specify settings, folder and filename patterns, for multiple databases at a time.
The default pattern filename pattern is
'{ServerName}${InstanceName}_{DatabaseName}_{BackupType}_{Partial}_{CopyOnly}_{Year}{Month}{Day}_{Hour}{Minute}{Second}_{FileNumber}.{FileExtension}',
A single command can be used to perform multiple operations, eg both backup all user databases and verify the backups, and clean up old backups :
EXECUTE dbo.DatabaseBackup
#Databases = 'USER_DATABASES',
#Directory = 'C:\Backup',
#BackupType = 'FULL',
#Verify = 'Y',
#Compress = 'Y',
#CheckSum = 'Y',
#CleanupTime = 24
Try this:
EXEC('BACKUP DATABASE [Company] TO DISK = N''G:\SQLBackups\INSTANCE1\MonthEndBackup\Company\MonthEndBackup' + CURRENT_TIMESTAMP + '.bak'' WITH NOFORMAT, COPY_ONLY,INIT,
NAME = N''MonthEndBackup'', SKIP, NOREWIND, NOUNLOAD, STATS = 10
')

Sending query results via email via email attachment every first day of every month on SQL Server 2012

My requirement:
Send the query result via email attachment on first day of every month.
The work I've been doing manually:
I have to run this query every first day of each month by changing the date range.
Then I export the result acquired in .csv format and send this csv file as an attachment
I needed suggestions from you people on how shall I automate this process:
Shall I set up a Job on SQL Server 2012, but yes, the I'll have to modify the date range.
Please suggest on how to move forward.
Any help, much appreciated.
As you mentioned, Create a Job and schedule it to run on first day of every month. Considering you have enough knowledge on creating a job.
Go to Job properties -> schedules -> and make the following setting
Occurs every first day of every 1 month(s) at 12:00:00. Schedule will
be used starting on 07-12-2016.
Change the timing(at which time it should run on first day of month) based on your business requirement. It can be set under Daily frequency-> Occurs once at:
This process can also be automated by another way by using a Windows batch file.You can schedule it using Windows scheduler.
Below will be contents of batch file
Echo off
sqlcmd -u <username> -p <password> -S <server name> -d <database name> -i <sql file location> -o <output result file location>
Powershell.exe -executionpolicy remotesigned -File <location of powershell file>
The powershell file trigger an email when bat file is run.
Contents of powershell file
$smtpserver = "<smtp server name>"
$from="mail id"
$to="<mail id"
$a = Get-Date
$subject= "<subject line> `r"+ $a.Month +"/"+$a.Day +"/"+ $a.Year
$body=""
$attachment="File location"
Thanks,`n "
$mailer = new-object Net.Mail.SMTPclient($smtpserver)
$msg = new-object Net.Mail.MailMessage($from,$to,$subject,$body,$data1,$a)
$msg.IsBodyHTML = $true
$mailer.send($msg)
I use SQL Agent for send results via email like this:
/*
First you should set up SQL Mail Profile.
Please change #dbName, #SQLscript, #mailbody and mail account values. When changing your #SQLscript value be careful that replace (with CTRL+H) single quota (') to double quotas ('').
*/
DECLARE #dbName nvarchar(50), #SQLscript nvarchar(4000), #subject varchar(100), #mailfrom varchar(100), #mailbody nvarchar(4000), #jobName varchar(100)
SELECT #jobName = name from msdb..sysjobs where job_id = $(ESCAPE_NONE(JOBID))
SELECT #mailfrom = ##SERVICENAME + ' <' + cast(SERVERPROPERTY('ComputerNamePhysicalNETBIOS') as varchar(50)) + '#domain.com>'
SELECT #subject = N'SQL Server Job Result [Job: ' + #jobName + ']'
SELECT #dbName = 'Database'
SELECT #SQLscript = '
INSERT INTO [Database].[Schema].[Table] (
Column1
,Column2
) VALUES (
''Value1''
,''Value2'' )
'
SELECT #mailbody = N'
Depending on case number 1234-5678-90 your script executed on <b>' + ##SERVERNAME + N'</b> instance and <b>' + #dbName + '</b> database. Script info and results are shown below. <br><br>' +
'<b>Script: </b><br>' + #SQLscript + '<br><br>' +
'<b>Result: </b><br>'
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'sqlmailprofile',
#recipients = '<mail1#domain.com>;<mail2#domain.com>',
#copy_recipients = '<mail3#domain.com>',
#from_address = #mailfrom,
#reply_to = '<mail3#domain.com>',
#subject = #subject,
#body = #mailbody,
#body_format = 'HTML',
#importance = 'HIGH',
#execute_query_database = #dbName,
#query = #SQLscript
/* If you want to send results with attached file:
#attach_query_result_as_file = 1,
#query_attachment_filename = 'script_output.csv',
#query_result_separator=#tab,
#query_result_width =32767,
#query_result_no_padding=1,
#exclude_query_output=1,
#query_result_header=1
*/

SQLCMD - SQL Server Job

suppose below is my query.
DECLARE #INT INT
SET #INT = (SELECT COUNT(1) FROM MyTable)
IF (#INT = 0)
RAISERROR('Fail',16,1)
I want to use this query and create a SQL Server job using "Operating System (CmdExec)" type.
I want to SQL Job step to be successful if #INT <> 0 and fail if #INT = 0.
How can I write the cmd?
My try (and it doesn't work)...the server is different than where I will be setting up the job.
sqlcmd -S 123.45.67.890 -E -V15 -d MyDB -Q "DECLARE #INT INT
SET #INT = (SELECT COUNT(1) FROM MyTable)
IF (#INT = 0)
RAISERROR('Fail',16,1)" -b
Job failure msg.
Executed as user: LocalSVR\USER. Msg 105, Level 15, State 1, Server RemoteSVR, Line 1 Unclosed quotation mark after the character string 'DECLARE #INT INT '. Process Exit Code 15. The step failed.
Please note, the step fails for the same reason when MyTable has 1+ record(s).
Update: As per Scott's suggestion, I changed the formatting (removed line breaks) and it seems to work. #Scott, not sure how to mark your comment as answer. If you can write a response, I will mark it as answer. Cheers!!!
You're trying to execute multiple lines as opposed to a single query. You can get round that by using IF NOT EXISTS
SQLCMD -b -S"MyServer" -d"MyDatabase" -Q"IF NOT EXISTS(SELECT * FROM MyTable) RAISERROR('Fail',16,1)"
Note that the -b (On error batch abort) option means that SQLCMD itself will fail giving you a Trappable ErrorLevel

How to check when autogrowth is done last?

In sql server 2005, the autogrowth is enabled by size.
Is there any way to check when autogrowth on data and log file happened last?
SSMS, right click your db, go to reports->standard reports->disk usage and look for Autogrow/Autoshrink events .
Hopefully you have the correct trace levels set up, if not you might have some issues finding out history.
Here's how to do it without using the sql reports(link, followed by relevant TSQL):
https://sqlblog.org/2007/01/11/reviewing-autogrow-events-from-the-default-trace
DECLARE #path NVARCHAR(260);
SELECT
#path = REVERSE(SUBSTRING(REVERSE([path]),
CHARINDEX('\', REVERSE([path])), 260)) + N'log.trc'
FROM sys.traces
WHERE is_default = 1;
SELECT
DatabaseName,
[FileName],
SPID,
Duration,
StartTime,
EndTime,
FileType = CASE EventClass
WHEN 92 THEN 'Data'
WHEN 93 THEN 'Log'
END
FROM sys.fn_trace_gettable(#path, DEFAULT)
WHERE
EventClass IN (92,93)
ORDER BY
StartTime DESC;