How can we schedule sql server agent job to fetch all records from the table to the CSV file end of every week in ssms, give me steps to complete task .

NAVINN T 20 Reputation points
2023-08-06T10:55:23.6566667+00:00

How can we schedule sql server agent job to fetch all records from the table to the CSV file end of every week in ssms, give me steps to complete task .

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
14,494 questions
{count} votes

3 answers

Sort by: Most helpful
  1. Gérald Döserich 765 Reputation points
    2023-08-06T11:58:37.7366667+00:00
    0 comments No comments

  2. Amira Bedhiafi 31,391 Reputation points
    2023-08-06T12:00:25.5166667+00:00

    While creating the job, in the step provide the SQL command to export the data.

    Select "Transact-SQL script (T-SQL)".

    Select the database containing the table you want to export.

    You can use a command with BCP like this:

       DECLARE @cmd varchar(1000)
         SET @cmd = 'bcp "SELECT * FROM YourDatabase.dbo.YourTable" queryout "C:\path\to\your\file.csv" -c -t, -T -S ' + @@servername
         EXEC xp_cmdshell @cmd
    

    Then try to create a new schedule for this job with the following

    • Frequency: Select "Weekly".
    • Recurs every: 1 week.
    • On: Choose the day of the week you want the job to run.
    • Start time: Set the time you want the job to run.

    Make sure that the SQL Server Agent service is running, as it is required to execute scheduled jobs.

    The account running the SQL Server Agent job must have sufficient permissions to execute the BCP command and write to the file system.

    • The xp_cmdshell command might be disabled on your server for security reasons. If it's necessary to enable it, you can do so by running:
     EXEC sp_configure 'show advanced options', 1;
      RECONFIGURE;
      EXEC sp_configure 'xp_cmdshell', 1;
      RECONFIGURE;
    

  3. Erland Sommarskog 120.2K Reputation points MVP
    2023-08-06T12:08:52.1733333+00:00

    The first step is to determine the exact requirements. What table? Where should the file land? What is the exact format of the file? Can you go with just plain commas or semicolons as the delimiter, or you need to consider that the delimiters may be in the data? What is the purpose of the file? What other system will ingest it? What tool do you want to use to generate the file? Many sites use SSIS, SQL Server Integration Services, but far from all.

    Once you have the code to produce the file, scheduling the job in Agent should be the easiest part.

    If you have further questions, please let us know.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.