Click here to Skip to main content
15,894,017 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
how to find folder size using sql scripts?

[OP's answer moved to question]
Hi here is the code to find.

but the catch is with this code i can find size of files inside the folder. Not the sum of all files and subfolder size.and if i have sublfoders not an indivdual files then it shows 0 bytes.

May i known why and how to calculate size of folder including subfolder size.

use tempdb
set nocount on
 
declare @line varchar(255)
declare @path varchar(255)
declare @command varchar(255)
 
if object_id('#output') is not null and objectproperty(object_id('#output'),
'IsTable') = 1
drop table #output
 
create table #output (line varchar(255))
 
set @path = 'C:\Program Files'
set @command = 'dir "' + @path +'"'
 
insert into #output
exec master.dbo.xp_cmdshell @command
 
select @line = ltrim(replace(substring(line, charindex(')', line)+1,len(line)), ',', ''))
from #output where line like '%File(s)%bytes'
 
print @line + ' (This is a string and the value ignores the size of any sub-folders)'
Posted
Updated 27-Jun-11 4:25am
v3

1 solution

A simple google search using a cut-and-paste of your question text returned about 2.6 million results.
I found an answer to your question in the first 10 results.

how to find folder size using sql scripts[^]

from http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=156137[^]:
"You can use xp_cmdshell to call the dir command with the appropriate flags, or maybe a Powershell script, but that's about it. There are no native SQL commands to provide that information."

[edit]
As per your additional information, I am not entirely familiar with doing this, but you may need to create a process that will create a running tally of the sum of file sizes and then iterate through each sub folder. This would be a very inefficient and time consuming process if the directory structure gets to any substantial size, so hopefully someone can provide you better info as well.
[/edit]
 
Share this answer
 
v3

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