?
Solved

batch file that sorts a table biased on the content of the 2nd column to a csv file named by the most common value.

Posted on 2016-07-28
8
Medium Priority
?
55 Views
Last Modified: 2016-08-03
so i have a sql database that i would like to extract data into a CSV file using a batch file that runs periodically

the data is as follows
NOTE: sample of data actual table is around 100k lines long
Base code,Ident A,Ident B,District,U ID,
PA,2,5,PHELPS,001
SA,4.3,SIVELLE,002
MAR,1,5,MARYS,003
MAR,2,5,MARYS,004
M4,5,3,MARYS,005
S6,6,7,PHELPS,006
S6,5,7,PHELPS,007
LM5,3,6,NODE,008

Extracted to files like below

MAR.csv
MAR,
M4,

S6.csv
S6,
PA,

SA.csv
SA,

LM5.csv
LM5,

I would like a batch solution, I can already set the database to be extracted to a csv if that makes it easier
using a Microsoft sql server 2008 r2 with the sql server management studio 2008 r2 aswell
0
Comment
Question by:csePixelated
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 4
8 Comments
 
LVL 70

Expert Comment

by:Qlemo
ID: 41733300
Just to get it correct: Each CSV file should contain Base Codes having the same District? And within each district the most common base code determines the file name?
0
 
LVL 1

Author Comment

by:csePixelated
ID: 41733342
yes
0
 
LVL 70

Accepted Solution

by:
Qlemo earned 2000 total points
ID: 41733933
Gosh. You are loosing all relevant information. No clue what this export should be for.

Assuming following definition:
create table tst_EE
([Base Code] varchar(10),
 [Ident A] smallint,
 [Ident B] smallint,
 [District] varchar(10),
 [U ID] char(3)
 )

insert into tst_ee values
('PA' ,2,5,'PHELPS' ,'001'),
('SA' ,4,3,'SIVELLE','002'),
('MAR',1,5,'MARYS'  ,'003'),
('MAR',2,5,'MARYS'  ,'004'),
('M4' ,5,3,'MARYS'  ,'005'),
('S6' ,6,7,'PHELPS' ,'006'),
('S6' ,5,7,'PHELPS' ,'007'),
('LM5',3,6,'NODE'   ,'008')

Open in new window


There are several different approaches. I'm choosing a PowerShell solution getting pre-processed SQL data directly, because that does not require complex processing. The first two variables need to be adapted to your environment.
Because your "CSV" files contain just a single "column", I will generate a simple text file instead of a CSV.
$ConStr = 'Server=MsSqlServer\Instance; Database=TheDB; Integrated Security=sspi'
$path = 'C:\temp\EE\Results\'

# Get data including target filename (without extenstion and path)
$set = new-object system.data.dataset
(new-object System.Data.SqlClient.SqlDataAdapter (@"
  with
    vals as (select [Base Code], District, cnt=count(*) from tst_EE group by District, [Base Code]),
    rnks as (select [Base Code], District, rnk=dense_rank() over (partition by District order by cnt desc) from vals)
  select filename=rnks.[Base Code], vals.District, vals.[Base Code], vals.cnt
    from vals join rnks on vals.District = rnks.District and rnks.rnk = 1
  order by district, cnt desc
"@, $ConStr)).Fill($set) | out-null

# Process the results
$csv = $null
$data = @()
$set.Tables[0] | % {
  if ($csv -eq $_.filename) {
    $data += $_.{Base Code}
  } else {
    # need to write out the file now
    if ($data) { $data | Out-File "$path$csv.csv" }
    $csv = $_.filename
    $data = @($_.{Base Code})
    Write-Host "Processing district $($_.District) -> $csv.csv"
  }
  Write-Host "`t",$_.{Base Code},$_.District,$_.Cnt
}
# need to write out last file
$data | Out-File "$path$csv.csv"

Open in new window

There is some debug/progress output to the console included, though the script should be fast.
0
Ransomware-A Revenue Bonanza for Service Providers

Ransomware – malware that gets on your customers’ computers, encrypts their data, and extorts a hefty ransom for the decryption keys – is a surging new threat.  The purpose of this eBook is to educate the reader about ransomware attacks.

 
LVL 1

Author Comment

by:csePixelated
ID: 41735185
Qlemo, a ps1 script will indeed work, where do I plug in what table on the database I am referencing?
can the ip address be used in place of the servers name?
what do i put if it is the default sql instance?
sorry this is very new to me.
0
 
LVL 70

Expert Comment

by:Qlemo
ID: 41735207
The table name I used is tst_EE. Just replace it. Or do you want to have a variable for it too?
0
 
LVL 1

Author Comment

by:csePixelated
ID: 41735218
No variable needed, I was simply confused, ty.
0
 
LVL 1

Author Comment

by:csePixelated
ID: 41735236
I am very new to Ps1 script, so i apologize in advance for all the questions.
ill admit i did not put the precise data down as the information i am dealing with cannot be posted to any degree, however i see no reason not to update you on the actual structure.

I believe i changed all the variables, I am running the .ps1 script from a windows 7 workstation, do i need to be running it from an sql server for it to work?

$ConStr = 'Server=cdiserv2\Instance; Database=MISCELLANEOUS; Integrated Security=sspi'
$path = 'Z:\Sync\Dealer Account Billing Sheets\LINE CODES\'

# Get data including target filename (without extenstion and path)
$set = new-object system.data.dataset
(new-object System.Data.SqlClient.SqlDataAdapter (@"
  with
    vals as (select [LineCode], Name, cnt=count(*) from "Line Codes" group by Name, [LineCode]),
    rnks as (select [LineCode], Name, rnk=dense_rank() over (partition by Name order by cnt desc) from vals)
  select filename=rnks.[LineCode], vals.Name, vals.[LineCode], vals.cnt
    from vals join rnks on vals.Name = rnks.Name and rnks.rnk = 1
  order by Name, cnt desc
"@, $ConStr)).Fill($set) | out-null

# Process the results
$csv = $null
$data = @()
$set.Tables[0] | % {
  if ($csv -eq $_.filename) {
    $data += $_.{LineCode}
  } else {
    # need to write out the file now
    if ($data) { $data | Out-File "$path$csv.csv" }
    $csv = $_.filename
    $data = @($_.{LineCode})
    Write-Host "Processing Name $($_.Name) -> $csv.csv"
  }
  Write-Host "`t",$_.{LineCode},$_.Name,$_.Cnt
}
# need to write out last file
$data | Out-File "$path$csv.csv"

Open in new window


be advised I do not use the SA login for sql, i use windows authentication
0
 
LVL 70

Assisted Solution

by:Qlemo
Qlemo earned 2000 total points
ID: 41735325
The authentication is set up to use Windows Authentication (sspi).
You should be able to run the script on your workstation, at least if having the MSSQL Native Client installed.
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

When you receive another warning that your shared drive is almost full and you have asked your users to clean out old files again and again, here is a single command that may help. This command will place all the files that have not been used rec…
In this article we will get to know that how can we recover deleted data if it happens accidently. We really can recover deleted rows if we know the time when data is deleted by using the transaction log.
Michael from AdRem Software explains how to view the most utilized and worst performing nodes in your network, by accessing the Top Charts view in NetCrunch network monitor (https://www.adremsoft.com/). Top Charts is a view in which you can set seve…
In this video you will find out how to export Office 365 mailboxes using the built in eDiscovery tool. Bear in mind that although this method might be useful in some cases, using PST files as Office 365 backup is troublesome in a long run (more on t…

765 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question