<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>PowerShell.nu &#187; SQL</title>
	<atom:link href="http://www.powershell.nu/category/sql/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.powershell.nu</link>
	<description></description>
	<lastBuildDate>Wed, 14 Jul 2010 22:17:44 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Another Handy SQL function in PowerShell</title>
		<link>http://www.powershell.nu/2009/01/30/another-handy-sql-function-in-powershell/</link>
		<comments>http://www.powershell.nu/2009/01/30/another-handy-sql-function-in-powershell/#comments</comments>
		<pubDate>Fri, 30 Jan 2009 11:29:34 +0000</pubDate>
		<dc:creator>Niklas Goude</dc:creator>
				<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://www.powershell.nu/?p=392</guid>
		<description><![CDATA[The Get-SQL function retrieved data from SQL and presented it in a HashTable Array. Let&#8217;s create a similar function that we can use when updating, inserting or deleting data from an SQL server. function Set-SQL ([string]$Query,[string]$ConnString) { if ($ConnString) { if($ConnString -match '"*"') { $ConnString = $ConnString.TrimStart('"') $ConnString = $ConnString.TrimEnd('"') } } else { # [...]]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://www.powershell.nu/2009/01/27/handy-sql-function-in-powershell/">Get-SQL</a> function retrieved data from SQL and presented it in a HashTable Array.</p>
<p />
Let&#8217;s create a similar function that we can use when updating, inserting or deleting data from an SQL server.</p>
<p />
<pre>
<strong>
function Set-SQL ([string]$Query,[string]$ConnString) {

if ($ConnString) {

	if($ConnString -match '"*"') {
		$ConnString = $ConnString.TrimStart('"')
		$ConnString = $ConnString.TrimEnd('"')
	}

} else {

	# Default ConnectionString
	$ConnString =
	"server=SQL;database=master;trusted_connection=true;"

}

$Connection = New-Object System.Data.SQLClient.SQLConnection

$Connection.ConnectionString = $ConnString
$Connection.Open()

$Command = New-Object System.Data.SQLClient.SQLCommand
$Command.Connection = $Connection
$Command.CommandText = $Query

return $Reader = $Command.ExecuteNonQuery()

$Connection.Close()

}
</strong>
</pre>
<p />
Examples on Running the Function</p>
<p />
<pre>
<strong>
PS > Set-SQL -Query "INSERT INTO Region (RegionID,RegionDescription) VALUES ('5','Even More North')" `
-ConnString "server=Server;database=Northwind;trusted_connection=true;"

PS > Set-SQL "DELETE * FROM Region WHERE RegionID = '5'" `
-ConnString "server=Server;database=Northwind;trusted_connection=true;"
</strong>
</pre>
<p />
]]></content:encoded>
			<wfw:commentRss>http://www.powershell.nu/2009/01/30/another-handy-sql-function-in-powershell/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Handy SQL Function in PowerShell</title>
		<link>http://www.powershell.nu/2009/01/27/handy-sql-function-in-powershell/</link>
		<comments>http://www.powershell.nu/2009/01/27/handy-sql-function-in-powershell/#comments</comments>
		<pubDate>Tue, 27 Jan 2009 09:20:07 +0000</pubDate>
		<dc:creator>Niklas Goude</dc:creator>
				<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://www.powershell.nu/?p=382</guid>
		<description><![CDATA[In a previous post I described a little about PowerShell and SQL, how to connect and how to handle different queries through PowerShell. Now let&#8217;s put it all togheter and create a more handy function. function Get-SQL ([string]$Query,[string]$ConnString) { if ($ConnString) { if($ConnString -match '"*"') { $ConnString = $ConnString.TrimStart('"') $ConnString = $ConnString.TrimEnd('"') } } else [...]]]></description>
			<content:encoded><![CDATA[<p>In a previous post I described a little about PowerShell and SQL, how to connect and how to handle different queries through PowerShell.</p>
<p />
Now let&#8217;s put it all togheter and create a more handy function.</p>
<p />
<pre>
<strong>
function Get-SQL ([string]$Query,[string]$ConnString) {

if ($ConnString) {

	if($ConnString -match '"*"') {
		$ConnString = $ConnString.TrimStart('"')
		$ConnString = $ConnString.TrimEnd('"')
	}

} else {

	# Default Connection String
	$ConnString =
	"server=ServerName;database=DbName;trusted_connection=true;"

}

$Connection = New-Object System.Data.SQLClient.SQLConnection

$Connection.ConnectionString = $ConnString
$Connection.Open()

$Command = New-Object System.Data.SQLClient.SQLCommand
$Command.Connection = $Connection
$Command.CommandText = $Query

$Reader = $Command.ExecuteReader()
$Counter = $Reader.FieldCount
while ($Reader.Read()) {
	$SQLObject = @{}
	for ($i = 0; $i -lt $Counter; $i++) {
		$SQLObject.Add(
			$Reader.GetName($i),
			$Reader.GetValue($i));
	}
	$SQLObject
}

$Connection.Close()

}
</strong>
</pre>
<p />
Examples on Running the Function:</p>
<p />
<pre>
<strong>
PS > Get-SQL "SELECT * FROM Products"

PS > Get-SQL "SELECT * FROM Products" `
-Server "server=NewServer;database=DbName;trusted_connection=true;"
</strong>
</pre>
<p />
]]></content:encoded>
			<wfw:commentRss>http://www.powershell.nu/2009/01/27/handy-sql-function-in-powershell/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>SQL through PowerShell</title>
		<link>http://www.powershell.nu/2009/01/26/sql-through-powershell/</link>
		<comments>http://www.powershell.nu/2009/01/26/sql-through-powershell/#comments</comments>
		<pubDate>Mon, 26 Jan 2009 20:29:31 +0000</pubDate>
		<dc:creator>Niklas Goude</dc:creator>
				<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://www.powershell.nu/?p=379</guid>
		<description><![CDATA[Working with Databases through PowerShell can be a little tricky since PowerShell doesn&#8217;t contain any SQL CmdLets. Let&#8217;s start connecting to our SQL database using the SQLConnection object: PS > $Connection = New-Object System.Data.SQLClient.SQLConnection PS > $Connection StatisticsEnabled : False ConnectionString : ConnectionTimeout : 15 Database : DataSource : PacketSize : 8000 ServerVersion : WorkstationId [...]]]></description>
			<content:encoded><![CDATA[<p>Working with Databases through PowerShell can be a little tricky since PowerShell doesn&#8217;t contain any SQL CmdLets. Let&#8217;s start connecting to our SQL database using the SQLConnection object:</p>
<p />
<pre>
<strong>
PS > $Connection = New-Object System.Data.SQLClient.SQLConnection
PS > $Connection
</strong>

StatisticsEnabled                : False
ConnectionString                 :
ConnectionTimeout                : 15
Database                         :
DataSource                       :
PacketSize                       : 8000
ServerVersion                    :
WorkstationId                    : Server
FireInfoMessageEventOnUserErrors : False
State                            : Closed
Site                             :
Container                        :
</pre>
<p />
Next, we have to set the ConnectionString, this defines which DataBase that we want to connect to.<br />
Note that the authentication method that is used in this example is integrated authentication. If you use non-integrated authentiacation, you can add &#8220;userid=username;password=password;&#8221; to the connection string.</p>
<p />
Note that the database we will use in these examples is Northwind which is a sample database from Microsoft that you can download for free at <a href='http://www.microsoft.com'>Microsoft.com</a></p>
<p />
<pre>
<strong>
PS > $Connection.ConnectionString =
"server=Server;database=Northwind;trusted_connection=true;"
PS > $Connection.ConnectionString
</strong>

server=Server;database=Northwind;trusted_connection=true;
</pre>
<p />
And when all is set, we open the Connection.</p>
<p />
<pre>
<strong>
PS > $Connection.Open()
</strong>
</pre>
<p />
When you are finished using your database, you can close it with the close() method.</p>
<p />
<pre>
<strong>
PS > $Connection.Close()
</strong>
</pre>
<p />
Now that we&#8217;ve opened a connection to our database, we can start with a couple of queries. The four basic queries are:</p>
<ul>
<li>SELECT</li>
<li>INSERT</li>
<li>UPDATE</li>
<li>DELETE</li>
</ul>
<p />
When executing queries, use the SQLCommand Object. Note that if you use INSERT, UPDATE or DELETE, you won&#8217;t get a value returned so you should use the ExecuteNonQuery() method. In case of SELECT, you should use the ExecuteReader() method. Let&#8217;s start looking at the SELECT query:</p>
<p />
Northwind contains a table called Products. So if we want to see all Columns in Products we would use &#8220;SELECT * from Products&#8221; to retrieve all columns and rows:</p>
<p />
Note. In order to retrieve the data from our database, we have to use the ExecuteReader() method and<br />
loop through it. Column Names are retrieved through .GetName() and values are retrieved through .GetValue()</p>
<p />
<pre>
<strong>
PS > $Command = New-Object System.Data.SQLClient.SQLCommand
PS > $Command.Connection = $Connection
PS > $Command.CommandText = "SELECT * FROM Products"

PS > $Reader = $Command.ExecuteReader()
PS > $Counter = $Reader.FieldCount
while ($Reader.Read()) {
	for ($i = 0; $i -lt $Counter; $i++) {
		@{ $Reader.GetName($i) = $Reader.GetValue($i); }
	}
}
</strong>
Name                           Value
----                           -----
ProductID                      1
ProductName                    Chai
SupplierID                     1
CategoryID                     1
QuantityPerUnit                10 boxes x 20 bags
UnitPrice                      18,0000
UnitsInStock                   39
UnitsOnOrder                   0
ReorderLevel                   10
Discontinued                   False
ProductID                      2
ProductName                    Chang
SupplierID                     1
CategoryID                     1
QuantityPerUnit                24 - 12 oz bottles
UnitPrice                      19,0000
UnitsInStock                   17
UnitsOnOrder                   40
ReorderLevel                   25
Discontinued                   False
ProductID                      3
ProductName                    Aniseed Syrup
SupplierID                     1
CategoryID                     2
QuantityPerUnit                12 - 550 ml bottles
UnitPrice                      10,0000
</pre>
<p />
If we want a specific Row in the table, we can specify it in our SELECT query.</p>
<pre>
<strong>
PS > $Command = New-Object System.Data.SQLClient.SQLCommand
PS > $Command.Connection = $Connection
PS > $Command.CommandText = "SELECT * FROM Products where ProductName = 'Röd kaviar'"

PS > $Reader = $Command.ExecuteReader()
PS > $Counter = $Reader.FieldCount
PS > while ($Reader.Read()) {
	for ($i = 0; $i -lt $Counter; $i++) {
		@{ $Reader.GetName($i) = $Reader.GetValue($i); }
	}
}
</strong>
Name                           Value
----                           -----
ProductID                      73
ProductName                    Röd Kaviar
SupplierID                     17
CategoryID                     8
QuantityPerUnit                24 - 150 g jars
UnitPrice                      15,0000
UnitsInStock                   101
UnitsOnOrder                   0
ReorderLevel                   5
Discontinued                   False
</pre>
<p />
And if we want to check out another table, all we have to do is change the SELECT query as shown below.</p>
<p />
<pre>
<strong>
PS > $Command = New-Object System.Data.SQLClient.SQLCommand
PS > $Command.Connection = $Connection
PS > $Command.CommandText = "SELECT * FROM Region"
PS > $Reader = $Command.ExecuteReader()
PS > $Counter = $Reader.FieldCount
PS > while ($Reader.Read()) {
	for ($i = 0; $i -lt $Counter; $i++) {
		@{ $Reader.GetName($i) = $Reader.GetValue($i); }
	}
}

</strong>
Name                           Value
----                           -----
RegionID                       1
RegionDescription              Eastern
RegionID                       2
RegionDescription              Western
RegionID                       3
RegionDescription              Northern
RegionID                       4
RegionDescription              Southern
</pre>
<p />
Let&#8217;s check out the INSERT query. INSERT is used when you want to add new data to a table. First specify the Columns that you want to INSERT into and the specify the Values.</p>
<p />
Let&#8217;s play a little with the Region table.</p>
<pre>
<strong>
PS > $Command = New-Object System.Data.SQLClient.SQLCommand
PS > $Command.Connection = $Connection
PS > $Command.CommandText =
	"INSERT INTO Region (RegionID,RegionDescription) VALUES ('5','Even More North')"
PS > $Command.ExecuteNonQuery()
</strong>
1
</pre>
<p />
The return value is 1 since the row was affected. </p>
<p />
Let&#8217;s check that the row really was affected by using a SELECT query:</p>
<pre>
<strong>
PS > $Command = New-Object System.Data.SQLClient.SQLCommand
PS > $Command.Connection = $Connection
PS > $Command.CommandText = "SELECT * FROM Region where RegionID = '5'"
PS > $Reader = $Command.ExecuteReader()
PS > $Counter = $Reader.FieldCount
PS > while ($Reader.Read()) {
	for ($i = 0; $i -lt $Counter; $i++) {
		@{ $Reader.GetName($i) = $Reader.GetValue($i); }
	}
}

</strong>
Name                           Value
----                           -----
RegionID                       5
RegionDescription              Even More North
</pre>
<p />
The UPDATE query modifies existing data. It&#8217;s often used with a WHERE clause to limit the range of affect to the specified rows. Let&#8217;s UPDATE the row that we INSERTED above.</p>
<p />
<pre>
<strong>
PS > $Command = New-Object System.Data.SQLClient.SQLCommand
PS > $Command.Connection = $Connection
PS > $Command.CommandText =
"UPDATE Region set RegionDescription = 'Go West' WHERE RegionID = '5'"

PS > $Command.ExecuteNonQuery()
</strong>
1
</pre>
<p />
And again, we check that our row was affected.</p>
<p />
<pre>
<strong>
PS > $Command = New-Object System.Data.SQLClient.SQLCommand
PS > $Command.Connection = $Connection
PS > $Command.CommandText = "SELECT * FROM Region where RegionID = '5'"
PS > $Reader = $Command.ExecuteReader()
PS > $Counter = $Reader.FieldCount
PS > while ($Reader.Read()) {
	for ($i = 0; $i -lt $Counter; $i++) {
		@{ $Reader.GetName($i) = $Reader.GetValue($i); }
	}
}

</strong>
Name                           Value
----                           -----
RegionID                       5
RegionDescription              Go West
</pre>
<p />
DELETE will remove data from the database.</p>
<pre>
<strong>
PS > $Command = New-Object System.Data.SQLClient.SQLCommand
PS > $Command.Connection = $Connection
PS > $Command.CommandText = "DELETE * FROM Region WHERE RegionID = '5'"
PS > $Command.ExecuteNonQuery()
</strong>
1
</pre>
<p>And, finally, we check that the data really was deleted.</p>
<pre>
<strong>
PS > $Command = New-Object System.Data.SQLClient.SQLCommand
PS > $Command.Connection = $Connection
PS > $Command.CommandText = "SELECT * FROM Region"
PS > $Reader = $Command.ExecuteReader()
PS > $Counter = $Reader.FieldCount
PS > while ($Reader.Read()) {
	for ($i = 0; $i -lt $Counter; $i++) {
		@{ $Reader.GetName($i) = $Reader.GetValue($i); }
	}
}

</strong>
Name                           Value
----                           -----
RegionID                       1
RegionDescription              Eastern
RegionID                       2
RegionDescription              Western
RegionID                       3
RegionDescription              Northern
RegionID                       4
RegionDescription              Southern
</pre>
<p />
Below is the Code used in this post.</p>
<p />
<pre>
<strong>
$Connection = New-Object System.Data.SQLClient.SQLConnection
$Connection.ConnectionString =
  "server=Server;database=Northwind;trusted_connection=true;"
$Connection.Open()

$Query = "SELECT * FROM Products

$Command = New-Object System.Data.SQLClient.SQLCommand
$Command.Connection = $Connection
$Command.CommandText = $Query

$Reader = $Command.ExecuteReader()
$Counter = $Reader.FieldCount
while ($Reader.Read()) {
	for ($i = 0; $i -lt $Counter; $i++) {
		@{ $Reader.GetName($i) = $Reader.GetValue($i); }
	}
}
</strong>
</pre>
<p />
]]></content:encoded>
			<wfw:commentRss>http://www.powershell.nu/2009/01/26/sql-through-powershell/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>
