Click here to Skip to main content
15,881,755 members
Please Sign up or sign in to vote.
1.60/5 (2 votes)
See more:
I would like to know how to retrieve the size of a text file present on my drive in SQL.

What I have tried:

I have tried openrowset and my query goes like (select datalength(bulkcolumn) from openrowset(bulk 'C:\a.txt', single_clob) a)

But when I supply a variable instead of static path, the query does not compile.
Posted
Updated 28-Jun-16 1:26am
Comments
Afzaal Ahmad Zeeshan 27-Jun-16 12:22pm    
Why would you use SQL for this purpose when you can easily get the size in C# program.
ZurdoDev 27-Jun-16 16:04pm    
Because sometimes you need the result in SQL.
Afzaal Ahmad Zeeshan 27-Jun-16 16:14pm    
In such sometimes cases it is better to do things that you at least know the basics of. If you know nothing of the field you are trying these somethings on, results are always confusing. Such as in this case. In such cases my recommendation is to learn the basics instead of doing the advanced stuff. Just an opinion.
ZurdoDev 27-Jun-16 16:17pm    
A simple example. From a sql stored procedure you execute another stored procedure that outputs a file to the system. You check file size to make sure it exported correctly and if not you then return something from sql to the caller.

There are very real and very good use cases for wanting to see files from Sql.
Afzaal Ahmad Zeeshan 27-Jun-16 16:22pm    
Doesn't, File.WriteAllText(data); (in C#) work?

I mean, there are many ways you can check how data is being passed. You can get the data from readers and write it to the file streams from there too. Of course stored procedures can be fast, due to a bit caching and other stuff, sometimes memory is also a problem. :-)

Maybe, I am a bit more fan of KISS but however I cannot grasp this idea. Sorry Ryan.

1 solution

Per recommendation above, I'll post my tip/solution to get the ball rolling.

Stack has a nice example of the xp_cmdshell at:
[^]
Using the example you'll first need to configure the xp_cmdshell using sp_configure as shown below (if you don't have permissions, you'll need a System Admin or DBA to run it for you):

SQL
Use Master
GO

EXEC master.dbo.sp_configure 'show advanced options', 1
RECONFIGURE WITH OVERRIDE
GO

EXEC master.dbo.sp_configure 'xp_cmdshell', 1
RECONFIGURE WITH OVERRIDE
GO


Now you can run xp_cmdshell.

SQL
EXECUTE master.dbo.xp_cmdshell 'DIR "C:\YourDirectory" /A-D /B'


It works nice. It shows up in the results window in the familiar tabular format.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900