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:
Then just call it in SQL Server, either from a Command-step in a SQL Server Agent job, or via
xp_cmdshell
like so:Or, this same operation could be done in a PowerShell script.