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
42 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
  • 4
  • 4
8 Comments
 
LVL 68

Expert Comment

by:Qlemo
Comment Utility
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
Comment Utility
yes
0
 
LVL 68

Accepted Solution

by:
Qlemo earned 500 total points
Comment Utility
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
 
LVL 1

Author Comment

by:csePixelated
Comment Utility
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
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 
LVL 68

Expert Comment

by:Qlemo
Comment Utility
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
Comment Utility
No variable needed, I was simply confused, ty.
0
 
LVL 1

Author Comment

by:csePixelated
Comment Utility
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 68

Assisted Solution

by:Qlemo
Qlemo earned 500 total points
Comment Utility
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

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

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…
Occasionally there is a need to clean table columns, especially if you have inherited legacy data. There are obviously many ways to accomplish that, including elaborate UPDATE queries with anywhere from one to numerous REPLACE functions (even within…
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

744 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

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now