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
53 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 500 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
Is Your DevOps Pipeline Leaking?

Is your CI/CD pipeline a hodge-podge of randomly connected tools? You’ve likely got a tool to fix one problem & then a different tool to fix another, resulting in a cluster of tools with overlapping functionality. Learn how to optimize your pipeline with Gartner's recommendations

 
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 500 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

What Is Transaction Monitoring and who needs it?

Synthetic Transaction Monitoring that you need for the day to day, which ensures your business website keeps running optimally, and that there is no downtime to impact your customer experience.

Question has a verified solution.

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

If like me you are one who spends a lot of time working and scripting with cmd.exe, sometimes it is handy to be able to quickly view a calendar for a given month and year. This script will quickly do just that!  Save the code posted below to a .bat …
In this article I will describe the Detach & Attach method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
This video Micro Tutorial shows how to password-protect PDF files with free software. Many software products can do this, such as Adobe Acrobat (but not Adobe Reader), Nuance PaperPort, and Nuance Power PDF, but they are not free products. This vide…
In this video we outline the Physical Segments view of NetCrunch network monitor. By following this brief how-to video, you will be able to learn how NetCrunch visualizes your network, how granular is the information collected, as well as where to f…

705 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