Sql-server – How to read and increment a number in text file using TSQL

sql serversql-server-2008t-sql

I have a text file C:\abc.txt with a number 5 in the first line. I need to increment it into 6.

Please help me with the T_SQL syntax.

I have tried the following query to read the value but not able to update it.

DROP TABLE #UserLocation

CREATE TABLE #UserLocation(UserId numeric(3,0))     

BULK INSERT #UserLocation
    FROM 'C:\ABC\ABC.txt'  
    -- Path to the file.If this file is on server,be sure this file exists on the server.
    WITH 
    (
        ROWTERMINATOR ='\n', 
        --  New Line Feed (\n) automatically adds Carrige Return (\r)
        FIELDTERMINATOR = '\t', 
        --delimiter 
        FIRSTROW = 1
    )   

PRINT 'File data copied to Temp table'      

SELECT * FROM #UserLocation 

Best Answer

The simplest way to read and increment a numeric value in a text file would be to not do it in SQL Server, though you can still use SQL Server to cause it to happen.

You can create a CMD script as follows that accepts a single input parameter for the file name and then increments the value inside of that file by 1. If the file name does not exist, it will be created with an initial value of 0.

Just create a new text file in Windows Explorer and replace the entire name, including the extension, with: IncrementValue.cmd.

Then edit the file and paste in the following:

@ECHO OFF

SETLOCAL ENABLEDELAYEDEXPANSION

IF NOT EXIST %1 ECHO 0 > %1

FOR /F %%A IN ('TYPE %1') DO (
    SET /A NewTempValue=%%A+1
    ECHO !NewTempValue! > %1
)

REM Uncomment the following line to get the value back in xp_cmdshell
REM ECHO !NewTempValue!

Then just call it in SQL Server, either from a Command-step in a SQL Server Agent job, or via xp_cmdshell like so:

-- remove the ", NO_OUTPUT" if you need to get the new value back
EXEC xp_cmdshell N'IncrementValue.cmd MyFile.txt', NO_OUTPUT;

Or, this same operation could be done in a PowerShell script.