In SQL Server you can do this in a stored proc
using IF... ELSE
construct.
Here is the MSDN Documentation that explains how to use the construct...
The counting part will look like this-
IF ((SELECT COUNT(PC.id) FROM [server08].[db01].[dbo].[tblesrc01] PC) > 500)
BEGIN
TRUNC ...
INSERT ...
END
And for the saving data part : you can use bcp
command. It allows you to export the result set from a Transact-SQL
statement to a data file
. The Transact-SQL statement can be any valid statement that returns a results set, such as a distributed query or a SELECT statement joining several tables.
The following example exports the names from the AdventureWorks2008R2 Person.Person table into the Contacts.txt data file. The names are ordered by last name then first name.
The example is executed from the Microsoft Windows command prompt:
bcp "SELECT FirstName, LastName FROM AdventureWorks2008R2.Person.Person ORDER BY LastName, Firstname" queryout Contacts.txt -c -T
Executing bcp inside a stored procedure--
DECLARE @job NVARCHAR(100)
SET @job ='execute_bcp'
EXEC msdb..sp_add_job @job_name = @job,
@description = 'Execute bcp command',
@owner_login_name = 'sa',
@delete_level = 1
EXEC msdb..sp_add_jobstep @job_name = @job,
@step_id = 1,
@step_name ='Command Shell Execution', @subsystem = 'CMDEXEC',
@command = 'bcp "SELECT Name FROM [DatabaseName].[dbo].[Employees]" queryout "filepath.txt" -c -T',
@on_success_action =1
EXEC msdb..sp_add_jobserver @job_name =@job
EXEC msdb..sp_start_job @job_name = @job