<?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>Serge&#039;s Technology View &#187; Fun stuff with SQL Server</title>
	<atom:link href="http://blog.dragonsoft.us/category/technology/fun-stuff-with-sql-server/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.dragonsoft.us</link>
	<description>Talk about Technologies, Software Architecture and Management</description>
	<lastBuildDate>Tue, 20 Apr 2010 14:42:38 +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>SQL Server: Tables, Views and missing columns</title>
		<link>http://blog.dragonsoft.us/2010/02/26/tables-views-missing-columns/</link>
		<comments>http://blog.dragonsoft.us/2010/02/26/tables-views-missing-columns/#comments</comments>
		<pubDate>Fri, 26 Feb 2010 13:42:30 +0000</pubDate>
		<dc:creator>Serguei Dosyukov</dc:creator>
				<category><![CDATA[Fun stuff with SQL Server]]></category>
		<category><![CDATA[invalid column]]></category>
		<category><![CDATA[invalid data]]></category>
		<category><![CDATA[refresh metadata]]></category>
		<category><![CDATA[refresh object]]></category>
		<category><![CDATA[refresh view]]></category>
		<category><![CDATA[script]]></category>
		<category><![CDATA[sp_refreshsqlmodule]]></category>
		<category><![CDATA[sp_refreshview]]></category>
		<category><![CDATA[sql server]]></category>
		<category><![CDATA[view schema]]></category>

		<guid isPermaLink="false">http://blog.dragonsoft.us/?p=1109</guid>
		<description><![CDATA[When it comes to non-schema-bound-views (NSB View) it is important to remember that there is no schema bound between objects used in the view and metadata for a view. Let&#8217;s look at the following scenario: -- Create Table_1 CREATE TABLE dbo.Table_1 (Col_A int NULL, Col_B numeric(18, 0) NULL, Col_C nvarchar(50) NULL) ON [PRIMARY] GO; -- -- [...]]]></description>
			<content:encoded><![CDATA[<p>When it comes to <strong>non-schema-bound-views</strong> (NSB View) it is important to remember that <strong>there is no schema bound between objects used in the view and metadata for a view</strong>.</p>
<p>Let&#8217;s look at the following scenario:</p>
<pre class="brush: sql;">-- Create Table_1
CREATE TABLE dbo.Table_1 (Col_A int NULL, Col_B numeric(18, 0) NULL, Col_C nvarchar(50) NULL) ON [PRIMARY]
GO;
--
-- Add data
INSERT dbo.Table_1 (Col_A, Col_B, Col_C) VALUES (10, 10.5, 'ABC');
INSERT dbo.Table_1 (Col_A, Col_B, Col_C) VALUES (20, 0.5, 'DEFG');
--
-- Create View
CREATE view [dbo].[vw_MyView] AS
SELECT TBL.*, (TBL.Col_A * TBL.Col_B) AS ColMult FROM dbo.Table_1 TBL
GO;</pre>
<p>Attempt to use the view would give the following result:</p>
<pre class="brush: plain;">Col_A, Col_B, Col_C, ColMult
=================================
10, 10.5, ABC, 105
20, 0.5, DEFG, 10
</pre>
<p>So far we are OK. But &#8220;fun&#8221; starts when a new column is added to the table</p>
<p><strong>Case #1 &#8211; bad:</strong></p>
<pre class="brush: sql;">ALTER TABLE dbo.Table_1 ADD Col_D nvarchar(10) NOT NULL DEFAULT 'A'</pre>
<p>Result of the view:</p>
<pre class="brush: plain;">Col_A, Col_B, Col_C, ColMult
=================================
10, 10.5, ABC, A
20, 0.5, DEFG, A</pre>
<p>Well&#8230; OK, it is not as bad as it seems since we would find the problem almost immediately in application since types of expected and retured data are incompatible. Bad situation, but manageable.</p>
<p><strong>Case #2 &#8211; catastrophic:<br />
</strong></p>
<pre class="brush: sql;">ALTER TABLE dbo.Table_1 ADD Col_D int NOT NULL DEFAULT 0</pre>
<p>Let&#8217;s look at the result now:</p>
<pre class="brush: plain;">Col_A, Col_B, Col_C, ColMult
=================================
10, 10.5, ABC, 0
20, 0.5, DEFG, 0</pre>
<p>ColMult now contains 0 (zero)!!! If we have significant logic which relays on that, then big troubles are coming our way.<br />
Now this is a catastrophic situation. And not easily visible. And off course work just fine on Developer&#8217;s machine&#8230;<br />
Testing&#8230; Testing&#8230; Testing&#8230;</p>
<p><strong>What just happened here?!!!</strong></p>
<p>This is when knowing <strong>non-schema-bound-views</strong> definition is important. And let&#8217;s remember &#8211; this is default state of any new view created.</p>
<p>First, what a difference between schema bound views and not bound.<br />
In order to create schema bound view special view attribute need to be specified. Let&#8217;s adjust original view definition as following:</p>
<pre class="brush: sql;">-- Alter View
ALTER VIEW [dbo].[vw_MyView] WITH SCHEMABINDING
AS
SELECT TBL.*, (TBL.Col_A*TBL.Col_B) AS ColMult FROM Table_1 TBL</pre>
<blockquote><p>SCHEMABINDING<br />
Binds the view to the schema of the underlying table or tables. When SCHEMABINDING is specified, the base table or tables cannot be modified in a way that would affect the view definition. The view definition itself must first be modified or dropped to remove dependencies on the table that is to be modified. When you use SCHEMABINDING, the select_statement must include the two-part names (schema.object) of tables, views, or user-defined functions that are referenced. All referenced objects must be in the same database.</p></blockquote>
<p>If we try executing script above to add the column error would occur: &#8220;Syntax &#8216;*&#8217; is not allowed in schema-bound objects.&#8221;</p>
<p>As you can see from definition of the attribute, view need to be defined explicitly with all columns listed. So if we were to have columns specified explicitly, then no problem would occur in the first place and is considered a good practice.</p>
<p>In our scenario above this is not an intent. Our view is designed to adjust itself to a table structure changes.<br />
Inconvenience&#8230; or advantage&#8230; I let you decide.</p>
<p><strong>Finding a cure</strong></p>
<p>Is there a way to fix the problem?</p>
<p>Dirty way of forcing the view metadata to be refreshed would be simply recreate the view using original script, but imagine you have 30+ of them &#8211; Not good, time consuming and error-prone.</p>
<p>There is a simple, universal and &#8220;human-error protected&#8221; way &#8211; after changes are applied to tables, simply refresh metadata of every view defined:</p>
<pre class="brush: sql;">DECLARE @Table_Name varchar(120)
DECLARE Refresh_Views CURSOR FOR
SELECT Table_Name FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'VIEW' AND TABLE_SCHEMA = 'dbo'
OPEN Refresh_Views
FETCH NEXT FROM Refresh_Views INTO @Table_Name
WHILE @@FETCH_STATUS = 0
BEGIN
EXEC sp_refreshview @Table_Name
print 'refreshed View for: ' + @Table_Name
FETCH NEXT FROM Refresh_Views INTO @Table_Name
END
CLOSE Refresh_Views
DEALLOCATE Refresh_Views</pre>
<p>In the script <strong>sp_refreshview </strong>would tell SQL Server to update the metadata for the all non-schema-bound views in current database.</p>
<p><strong>Note:</strong> Alternative: We can also use more generic command &#8211; <strong>sp_refreshsqlmodule </strong>- which &#8220;updates the metadata for the specified non-schema-bound stored procedure, user-defined function, view, DML trigger, database-level DDL trigger, or server-level DDL trigger in the current database. Persistent metadata for these objects, such as data types of parameters, can become outdated because of changes to their underlying objects.&#8221; This may be even better since it would allow to address any possible schema issues with any objects and not just views.</p>
<hr/><span style="font-size: 7pt">Copyright &copy; 2010 <strong><a href="http://blog.dragonsoft.us">Serge&#039;s Technology View</a></strong>. This Feed is for personal non-commercial use only.</span>]]></content:encoded>
			<wfw:commentRss>http://blog.dragonsoft.us/2010/02/26/tables-views-missing-columns/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>SQL tasks automation: apply scripts from folder</title>
		<link>http://blog.dragonsoft.us/2009/12/02/sql-tasks-automation-apply-scripts-from-folder/</link>
		<comments>http://blog.dragonsoft.us/2009/12/02/sql-tasks-automation-apply-scripts-from-folder/#comments</comments>
		<pubDate>Thu, 03 Dec 2009 03:18:13 +0000</pubDate>
		<dc:creator>Serguei Dosyukov</dc:creator>
				<category><![CDATA[Fun stuff with SQL Server]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[apply script]]></category>
		<category><![CDATA[apply sql script]]></category>
		<category><![CDATA[batch file]]></category>
		<category><![CDATA[osql]]></category>
		<category><![CDATA[sql automation]]></category>
		<category><![CDATA[sql script]]></category>
		<category><![CDATA[sql server]]></category>

		<guid isPermaLink="false">http://blog.dragonsoft.us/?p=1008</guid>
		<description><![CDATA[You will be amazed how common this question is: I have a folder with arbitrary set of SQL scripts and want to apply them all automatically. How do I do that? In other words: Having a folder &#8211; ex: C:\AutoSQLScripts &#8211; with some unknown set of SQL scripts And a SQL Instance where scripts need to be applied [...]]]></description>
			<content:encoded><![CDATA[<p>You will be amazed how common this question is:</p>
<blockquote><p><strong>I have a folder with arbitrary set of SQL scripts and want to apply them all automatically. How do I do that?</strong></p></blockquote>
<p>In other words:</p>
<ul>
<li>Having a folder &#8211; ex: C:\AutoSQLScripts &#8211; with some unknown set of SQL scripts</li>
<li>And a SQL Instance where scripts need to be applied</li>
<li>Run a scheduled task to perform the operation automatically.</li>
</ul>
<h3>Solution:</h3>
<p>First, lets figure out single operation - run SQL Script from command line in unattended mode using <strong><a href="http://msdn.microsoft.com/en-us/library/aa214012(SQL.80).aspx" target="_blank">osql</a></strong> utility:</p>
<pre class="brush: powershell;">::
osql -S MYSERVER -d MYDATABASE -E -i MySqlScript.sql  -o report.txt
::</pre>
<p>Where:</p>
<p><strong>-S</strong> indicates server name<br />
<strong>-d</strong> is an alternative to <em>USE db_name</em> inside the script<br />
<strong>-E</strong> indicates that trusted connection would be used<br />
<strong>-i</strong> identifies the file that contains a batch of SQL statements<br />
<strong>-o</strong> identifies the file that receives output from <strong>osql</strong></p>
<p>Simple so far&#8230;</p>
<p>Fun starts when we need to go through files in the folder. Using &#8220;magic&#8221; of Power Shell, it is also easy:</p>
<pre class="brush: powershell;">::
FOR /f &quot;TOKENS=*&quot; %%a IN ('dir /b &quot;%1*.sql&quot;') do ECHO %%a

::or

SET _PATH=%1
IF (NOT %_PATH%==&quot;&quot;) SET _PATH = '-p &quot;%_PATH%&quot;'
FORFILES %_PATH% -s -m *.* -c &quot;CMD /C ECHO @FILE&quot;
::</pre>
<p>Let&#8217;s ignore the end for now and concentrate on the syntax of the loop itself.</p>
<p><strong>FOR /f</strong> indicates that we need to perform a loop against a set of files specified in IN. To produce the set we are using <strong>&#8220;raw&#8221; dir </strong>of the folder, where %1 is, if specified, an input param of the batch file call.</p>
<p><strong>FORFILES</strong> is a little more complex and given here for comparison, yet produces the same result.</p>
<p><strong>Note: </strong><em>commands above work only with &#8220;local&#8221; (drive: based) locations. If you need apply scripts from Network folder, map it first as a local drive then apply scripts.</em></p>
<p>Now let&#8217;s combine SQL call with the batch processing and we would get the following <strong>ApplyScript.cmd</strong> which could be used to apply any scripts from current or specific folder to specified SQL Server/Database instance:</p>
<pre class="brush: powershell;">::
@ECHO OFF
SET _SERVER=MYSERVER
SET _DB=MYDATABASE

FOR /f &quot;TOKENS=*&quot; %%a IN ('dir /b %1*.sql') DO CALL osql -S %_SERVER% -d %_DB% -E -i %%a  -o report.txt
::</pre>
<p>Enjoy.</p>
<hr/><span style="font-size: 7pt">Copyright &copy; 2010 <strong><a href="http://blog.dragonsoft.us">Serge&#039;s Technology View</a></strong>. This Feed is for personal non-commercial use only.</span>]]></content:encoded>
			<wfw:commentRss>http://blog.dragonsoft.us/2009/12/02/sql-tasks-automation-apply-scripts-from-folder/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>SQL Server 2008: moving forward</title>
		<link>http://blog.dragonsoft.us/2009/01/09/sql-server-2008-moving-forward/</link>
		<comments>http://blog.dragonsoft.us/2009/01/09/sql-server-2008-moving-forward/#comments</comments>
		<pubDate>Fri, 09 Jan 2009 19:45:21 +0000</pubDate>
		<dc:creator>Serguei Dosyukov</dc:creator>
				<category><![CDATA[Fun stuff with SQL Server]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[dts in sql server 2008]]></category>
		<category><![CDATA[features]]></category>
		<category><![CDATA[sql server]]></category>
		<category><![CDATA[sql server 2008]]></category>
		<category><![CDATA[sql server 2008 data sheet]]></category>
		<category><![CDATA[sql server 2008 overview]]></category>

		<guid isPermaLink="false">http://blog.dragonsoft.us/?p=764</guid>
		<description><![CDATA[SQL Server 2008 has been available since Aug 6, 2008. This does not include CTP (Feb 2008) time-frame. We are close to the year milestone now. To my surprise there are still questions around if moving to a new version is necessary. This is especially difficult question to discuss/suggest when SQL Server 2005 adoption cycle is [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.microsoft.com/sqlserver/2008/en/us/default.aspx" target="_blank">SQL Server 2008</a> has been available since Aug 6, 2008. This does not include CTP (Feb 2008) time-frame.<br />
We are close to the year milestone now.</p>
<p>To my surprise there are still questions around if moving to a new version is necessary.</p>
<p>This is especially difficult question to discuss/suggest when SQL Server 2005 adoption cycle is just about being complete.</p>
<blockquote>
<ul>
<li>We all know about &#8220;have to wait until first SP is out&#8221; rule.</li>
<li>What is good about it to justify spending another chunk of IT budget?</li>
</ul>
</blockquote>
<p>To answer first question, there is a <a href="http://support.microsoft.com/kb/956717" target="_blank">cumulative update 1</a> available since Nov, 2008. One could count it as SP1.</p>
<p>To answer second question could be more difficult.</p>
<p>There is <a href="http://www.microsoft.com/sqlserver/2008/en/us/wp-sql-2008-overview.aspx" target="_blank">Product Overview</a> <a href="http://download.microsoft.com/download/6/9/d/69d1fea7-5b42-437a-b3ba-a4ad13e34ef6/SQL2008_ProductOverview.docx" target="_blank">White Paper</a> available along with <a href="http://download.microsoft.com/download/B/F/2/BF24C54E-5635-4C79-AFB4-0C3F840E79F4/SQLServer2008_Datasheet_Final.pdf" target="_blank">Data sheet</a> where main differences between 2005 and 2008 versions are highlighted.</p>
<p>As you could see many features are enterprise level, but many are to make life regular developers easier as well.</p>
<p>To summarise, while SQL Server 2008 could be considered just an extension to 2005, major enhancements are:</p>
<ol>
<li><strong>Transparent Data Encryption</strong> &#8211; add protection to your data storage without custom and usually process extensive solutions</li>
<li><strong>External Key Management</strong> &#8211; integrate 3rd party security keys and hardware</li>
<li><strong>Enhanced Auditing</strong> &#8211; monitor data access and modification</li>
<li><strong>Advanced Database Mirroring</strong> &#8211; data corruption protection, improved performance, new performance counters</li>
<li><strong>Hot CPU management</strong> &#8211; change hardware configurations without downtime (for supported hardware platforms)</li>
<li><strong>Performance improvements, Service Broker Scalability, Integrated Full-Text Search, Sparse Columns (&#8220;zero storage&#8221;), no 8,000 byte limit </strong>- manage allocated resources and priorities, query plans optimizations, data compression, backup compression (finally <img src='http://blog.dragonsoft.us/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  ), extended performance monitoring tools, 64 bit platform optimization (RAM, hardware, etc)</li>
<li><strong>SQL Server Integration Services (SSIS)</strong> improvements</li>
<li><strong>Policy-Based Management</strong></li>
<li><strong>Installation improvements</strong></li>
<li><strong>ADO.Net Entity Framework and CLR Integration</strong> &#8211; Object-Oriented style support instead of Table/Field approach</li>
<li><strong>LINQ</strong> &#8211; even though some pieces (?temporary solutions?) were available before, now LINQ becomes first-class citizen for SQL Server. Forget your T-SQL and program using LINQ syntax.</li>
<li><strong>T-SQL improvements</strong> &#8211; even though LINQ may be a way to go, T-SQL still is not forgotten with added support for <em>Table Value Parameters (TVP)</em>, <em>Object Dependencies Views and Functions</em>, new data types<em>: DATE, TIME, DATETIMEOFFSET, DATETIME2</em> allowing conserve storage space and improve time precision, <em>FILESTREAM, GEOGRAPHY</em> and <em>GEOMETRY </em> datatypes, and <em>HIERARCHYID</em> for better support of tree based data structures<br />
<strong>Compound operators</strong> &#8211; lovely &#8220;+=&#8221; syntax and <strong>in-line variable assignment </strong>DECLARE @myVar int = 5<br />
<strong>MERGE </strong>support &#8211; manage data inserts/updates in one SQL statement</li>
<li><strong>SQL Management Studio gets IntelliSense</strong> and other improvements and better Source Control integration</li>
<li><strong>SQL Management Studio T-SQL debugging</strong> &#8211; not as robust as it is in Visual Studio, but sufficient in many situations.</li>
<li><strong>Table Partitioning management</strong></li>
<li><strong>Hot-swap data connectors</strong> &#8211; easier support for disconnected data applications</li>
<li><strong>Improved MS Reporting Services and report builder</strong>- MS Word/Excel/SharePoint integration improved</li>
<li><strong>OLAP support improvements</strong></li>
</ol>
<p>Even if you decided to stay with 2000/2005 version, keep in mind a few things which will make your future upgrades easier.</p>
<p><strong>The list of features dropped/changed in SQL Server 2008.</strong></p>
<ol>
<li><strong>Deprecated SQL Server Features in SQL Server 2008</strong>
<ul>
<li>DTS support (<a href="http://msdn.microsoft.com/en-us/library/bb500440.aspx" target="_blank">link</a>) is replaced with SSIS (<a href="http://blog.scalabilityexperts.com/2008/02/14/the-key-sql-server-2008-bi-migration-dts-to-ssis-2008-part-1-of-2/" target="_blank">migration</a>)</li>
<li>ADHelper service</li>
<li>SOAP/HTTP endpoints, sys.http_endpoints, sys.endpoint_webmethods (Transact-SQL)</li>
</ul>
</li>
<li><strong>Discontinued SQL Server Features in SQL Server 2008</strong>
<ul>
<li>Some SMO Classes has been discontinued</li>
<li>Surface Area Configuration Tool (SAC)</li>
<li>Discontinued Command Prompt Parameters for SQL Server Setup</li>
</ul>
</li>
<li><strong>SQL Server Native Client has been upgraded with some behavior changes</strong></li>
</ol>
<p>How about some technical data and stats? To begin with, Microsoft team is no longer publicly presents any data which will show some benchmarks between versions, editions or between different database server platforms, so we have to relay on someone outside do the job.</p>
<p>Yes, comming with mathematical background I can agree with some arguments that this data is not accurate and always represent just what was tested in each particular case in each particular hardware configuration. With statistics being used by marketing department it can be very interesting.</p>
<p>Therefore, we have to be very sceptical about any stats presented anywhere. Nevertheless:</p>
<ul>
<li>Microsoft:
<ul>
<li><a href="http://www.microsoft.com/sqlserver/2008/en/us/compare.aspx" target="_blank">Microsoft SQL Server 2008: Compare</a> or count your money</li>
<li><a href="http://blogs.msdn.com/mattm/archive/2008/08/19/competitive-comparison-of-sql-server-2008-integration-services.aspx" target="_blank">Competitive Comparison of SQL Server 2008 Integration Services</a> by SSIS Team</li>
</ul>
</li>
<li>Some 3rd party data:
<ul>
<li>Count your time or <a href="http://sqlblog.com/blogs/joe_chang/archive/2008/08/17/large-query-performance-from-sql-server-2000-to-2008-32-64-bit.aspx" target="_blank">Large Query Performance from SQL Server 2000 to 2008, 32 &amp; 64-bit</a></li>
<li>Compare features or<span class="headertitle"> <a href="http://www.bostongis.com/PrinterFriendly.aspx?content_name=sqlserver2008_postgis_mysql_compare" target="_blank">Cross Compare SQL Server 2008 Spatial, PostgreSQL/PostGIS 1.3-1.4, MySQL 5-6</a></span></li>
</ul>
</li>
</ul>
<p>As far as my own experience with a new version - it has been positive and I would highly recommend to go with this upgrade.</p>
<hr/><span style="font-size: 7pt">Copyright &copy; 2010 <strong><a href="http://blog.dragonsoft.us">Serge&#039;s Technology View</a></strong>. This Feed is for personal non-commercial use only.</span>]]></content:encoded>
			<wfw:commentRss>http://blog.dragonsoft.us/2009/01/09/sql-server-2008-moving-forward/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>TIP: Installing SQL Server 2008 &#8211; reboot required check fails</title>
		<link>http://blog.dragonsoft.us/2008/11/08/tip-installing-sql-server-2008-reboot-required-check-fails/</link>
		<comments>http://blog.dragonsoft.us/2008/11/08/tip-installing-sql-server-2008-reboot-required-check-fails/#comments</comments>
		<pubDate>Sat, 08 Nov 2008 17:17:50 +0000</pubDate>
		<dc:creator>Serguei Dosyukov</dc:creator>
				<category><![CDATA[Fun stuff with SQL Server]]></category>
		<category><![CDATA[install problem]]></category>
		<category><![CDATA[PendingFileRenameOperations]]></category>
		<category><![CDATA[reboot required check]]></category>
		<category><![CDATA[reboot required check failed]]></category>
		<category><![CDATA[rebootrequiredcheck]]></category>
		<category><![CDATA[sql server 2008]]></category>
		<category><![CDATA[windows installer]]></category>

		<guid isPermaLink="false">http://blog.dragonsoft.us/?p=595</guid>
		<description><![CDATA[When installing SQL Server 2008 one can run into &#8220;&#8216;Reboot required check failed&#8221; situation. After seeing it few times already, I think a solution is worth mentioning. &#8220;Why don&#8217;t you just reboot?&#8221;, you say&#8230; Well, most likely it would not help you, but try it first. If this would not help, then try the following: [...]]]></description>
			<content:encoded><![CDATA[<p>When installing SQL Server 2008 one can run into &#8220;&#8216;Reboot required check failed&#8221; situation.</p>
<p>After seeing it few times already, I think a solution is worth mentioning.</p>
<p>&#8220;Why don&#8217;t you just reboot?&#8221;, you say&#8230; Well, most likely it would not help you, but try it first.<br />
If this would not help, then try the following:</p>
<ol>
<li>Start regedit.exe</li>
<li>Navigate to <strong>HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager</strong></li>
<li>Locate PendingFileRenameOperations</li>
<li>Remove any data associated with the value (you may want to export the value for later review)</li>
<li>Reboot and rerun installation, check should pass.</li>
</ol>
<p><strong>Update. </strong>As a respond to some comments about solution above not always work you may consider the following:</p>
<ul>
<li>Make sure that after you reboot entry in the registry does not reappear.<br />
If it does, remove it again, but do not reboot, just go ahead with installation process and click &#8220;ReRun&#8221;. Most likely you would be fine now.</li>
<li>You may also try and see that other <em><strong>ControlSet001, ControlSet002</strong>, etc</em> do not suffer from the same problem (solution mentioned by Mike Hills below).</li>
<li>There was mentioning that some installations of Visual Studio 2008 could cause check to fail as well. So if nothing from above helped, uninstall Visual Studio (comes with light version of SQL Server), install SQL Server and then reinstall Visual Studio again.</li>
</ul>
<p>Lets see why would entry reappear&#8230; This may happen if there is a driver or application which supports &#8220;recovery&#8221; mode or plain virus is around and after reboot it is trying to finish the deployment process again. In any situation try and look closer: what app file belongs to, if there are other solutions to the problem so that original process would finish properly, etc.</p>
<p><em>Update: </em>Recently I was working on the unrelated setup automation for Visual Studio and stepped on a hidden gem which may work here as well: when running setup from command prompt, Windows Installer accepts a parameter called <em>SkipRules</em>. It worth mention the following &#8220;<a href="http://technet.microsoft.com/en-us/library/ms144259.aspx" target="_blank">How to: Install SQL Server 2008 from the Command Prompt</a>&#8221; first and then look at desired parameter</p>
<blockquote><p>/SkipRules=VSShellInstalledRule RebootRequiredCheck</p></blockquote>
<p>We can ignore first rule, since it is VS related, but second is the one you may want to try.</p>
<hr/><span style="font-size: 7pt">Copyright &copy; 2010 <strong><a href="http://blog.dragonsoft.us">Serge&#039;s Technology View</a></strong>. This Feed is for personal non-commercial use only.</span>]]></content:encoded>
			<wfw:commentRss>http://blog.dragonsoft.us/2008/11/08/tip-installing-sql-server-2008-reboot-required-check-fails/feed/</wfw:commentRss>
		<slash:comments>20</slash:comments>
		</item>
		<item>
		<title>Tip: Get list of columns for the table</title>
		<link>http://blog.dragonsoft.us/2008/05/12/tip-get-list-of-columns-for-the-table/</link>
		<comments>http://blog.dragonsoft.us/2008/05/12/tip-get-list-of-columns-for-the-table/#comments</comments>
		<pubDate>Mon, 12 May 2008 20:26:47 +0000</pubDate>
		<dc:creator>Serguei Dosyukov</dc:creator>
				<category><![CDATA[Fun stuff with SQL Server]]></category>
		<category><![CDATA[list of columns]]></category>
		<category><![CDATA[sql]]></category>
		<category><![CDATA[sql server]]></category>
		<category><![CDATA[table]]></category>

		<guid isPermaLink="false">http://blog.dragonsoft.us/?p=180</guid>
		<description><![CDATA[When you dealing with dynamic SQL or unknown table structure, SQL meta data could help recover the missing information. There are two main system tables which give you such information: dbo.sysobjects dbo.syscolumns Example below shows how to gather column list for specified table. DECLARE @TABLENAME varchar(256), @COLUMNS varchar(4000) SET @TABLENAME = 'mytable' SET @COLUMNS = [...]]]></description>
			<content:encoded><![CDATA[<p>When you dealing with dynamic SQL or unknown table structure, SQL meta data could help recover the missing information.</p>
<p>There are two main system tables which give you such information:</p>
<ul>
<li>dbo.sysobjects</li>
<li>dbo.syscolumns</li>
</ul>
<p>Example below shows how to gather column list for specified table.</p>
<pre class="brush: sql;">DECLARE
  @TABLENAME varchar(256),
  @COLUMNS varchar(4000)

SET @TABLENAME = 'mytable'
SET @COLUMNS = ''

SELECT @COLUMNS = @COLUMNS + c.name + ', '
FROM syscolumns c
INNER JOIN sysobjects o ON o.id = c.id
WHERE o.name = @TABLENAME AND o.xtype='U'
ORDER BY colid

SET @COLUMNS = SUBSTRING(@COLUMNS, 1, Datalength(@COLUMNS) - 2)

SELECT @COLUMNS</pre>
<p>or if you prefer more generic approach</p>
<pre class="brush: sql;">DECLARE
  @TABLENAME varchar(256),
  @COLUMNS varchar(4000)

SET @TABLENAME = 'mytable'
SET @COLUMNS = ''

SET @COLUMNS = ''
SELECT @COLUMNS = @COLUMNS + COLUMN_NAME + ', '
FROM INFORMATION_SCHEMA.Columns
WHERE TABLE_NAME = @TABLENAME
ORDER BY ORDINAL_POSITION

SET @COLUMNS = SUBSTRING(@COLUMNS, 1, Datalength(@COLUMNS) - 2)
SELECT @COLUMNS</pre>
<p>Result is a coma-separated list of columns in the table in order they appear.</p>
<p><strong>Note</strong>. Check for xtype in the first example could be useful but not required, since you probably do not mix table name with any other object names. Otherwise, it would be necessary to ensure that you are looking at the table and not something else.<br />
Other possible values for this column are:</p>
<ul>
<li><strong>S</strong> &#8211; System tables</li>
<li><strong>U</strong> &#8211; User table</li>
<li><strong>TR</strong> &#8211; Triggers</li>
<li><strong>P</strong> &#8211; Stored procedure</li>
<li><strong>RF</strong> &#8211; Replication filter stored procedure</li>
<li><strong>X</strong> &#8211; Extended stored procedure</li>
<li><strong>V</strong> &#8211; View</li>
<li><strong>TF</strong> &#8211; Functions</li>
<li><strong>C</strong> &#8211; CHECK constraint</li>
<li><strong>D</strong> &#8211; DEFAULT constraint</li>
<li><strong>F</strong> &#8211; FOREIGN KEY constraint</li>
<li><strong>PK</strong> &#8211; PRIMARY KEY constraint (type is K)</li>
<li><strong>UQ</strong> &#8211; UNIQUE constraint (type is K)</li>
<li><strong>L</strong> &#8211; Log</li>
</ul>
<hr/><span style="font-size: 7pt">Copyright &copy; 2010 <strong><a href="http://blog.dragonsoft.us">Serge&#039;s Technology View</a></strong>. This Feed is for personal non-commercial use only.</span>]]></content:encoded>
			<wfw:commentRss>http://blog.dragonsoft.us/2008/05/12/tip-get-list-of-columns-for-the-table/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>SQL date operations: Last 90 days, Get Date from DateTime&#8230;</title>
		<link>http://blog.dragonsoft.us/2008/05/12/sql-date-operations-last-90-days-get-date-from-datetime/</link>
		<comments>http://blog.dragonsoft.us/2008/05/12/sql-date-operations-last-90-days-get-date-from-datetime/#comments</comments>
		<pubDate>Mon, 12 May 2008 20:14:16 +0000</pubDate>
		<dc:creator>Serguei Dosyukov</dc:creator>
				<category><![CDATA[Fun stuff with SQL Server]]></category>
		<category><![CDATA[date manipulations]]></category>
		<category><![CDATA[sql]]></category>
		<category><![CDATA[sql server]]></category>

		<guid isPermaLink="false">http://blog.dragonsoft.us/?p=179</guid>
		<description><![CDATA[I am continuing putting some common examples of operations for Microsoft SQL Server. In addition to some of the Date related code snippets published before, there are few more today: -- Last 90 days: select DATEADD(day, -90, GETDATE()) -- Get Date portion of DateTime value select DATEADD(d, 0, DATEDIFF(d, 0, getdate())) Copyright &#169; 2010 Serge&#039;s [...]]]></description>
			<content:encoded><![CDATA[<p>I am continuing putting some common examples of operations for Microsoft SQL Server.<br />
In addition to some of the Date related code snippets <a href="http://blog.dragonsoft.us/2008/02/05/first-day-last-day-of-the-month-and-sql/" target="_self">published before</a>, there are few more today:</p>
<pre class="brush: sql;">-- Last 90 days:
select DATEADD(day, -90, GETDATE())
-- Get Date portion of DateTime value
select DATEADD(d, 0, DATEDIFF(d, 0, getdate()))
</pre>
<hr/><span style="font-size: 7pt">Copyright &copy; 2010 <strong><a href="http://blog.dragonsoft.us">Serge&#039;s Technology View</a></strong>. This Feed is for personal non-commercial use only.</span>]]></content:encoded>
			<wfw:commentRss>http://blog.dragonsoft.us/2008/05/12/sql-date-operations-last-90-days-get-date-from-datetime/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>SQL Server Collation. An enemy or a friend?</title>
		<link>http://blog.dragonsoft.us/2008/04/15/sql-server-collation-an-enemy-or-a-friend/</link>
		<comments>http://blog.dragonsoft.us/2008/04/15/sql-server-collation-an-enemy-or-a-friend/#comments</comments>
		<pubDate>Wed, 16 Apr 2008 00:51:35 +0000</pubDate>
		<dc:creator>Serguei Dosyukov</dc:creator>
				<category><![CDATA[Fun stuff with SQL Server]]></category>
		<category><![CDATA[change database collation]]></category>
		<category><![CDATA[collation]]></category>
		<category><![CDATA[collationname]]></category>
		<category><![CDATA[sql server]]></category>

		<guid isPermaLink="false">http://blog.dragonsoft.us/?p=167</guid>
		<description><![CDATA[Is SQL Server Collation setting your enemy or your friend? How to change server default collation? In general, it is your friend, it will help SQL Server to figure out how to store character strings in different locale. It becomes even more important when data you are storing goes beyond regular ANSI charset (Chinese, Japanese, [...]]]></description>
			<content:encoded><![CDATA[<p>Is SQL Server Collation setting your enemy or your friend? How to change server default collation?</p>
<p>In general, it is your friend, it will help SQL Server to figure out how to store character strings in different locale. It becomes even more important when data you are storing goes beyond regular ANSI charset (Chinese, Japanese, etc.).</p>
<p>In my case I, from time to time work with Cyrillic. Being born and raised in Russia, I am native Russian speaker. As a result I am keeping Cyrillic enabled on my machine as main locale setting.</p>
<p>It is OK in many instances, but when it comes to SQL Server or some other applications which are trying to be smart in this area, it becomes a problem.</p>
<p>If you install SQL Server instance in such environment, you would get something like that</p>
<p>Let check collation for some database I have</p>
<pre class="brush: sql;">SELECT databasepropertyex(db_name(),'collation') AS collation_name</pre>
<p>In my case result would be</p>
<p> Cyrillic_General_CI_AS</p>
<p>If you are at home, it may be fine, but at work when your primary locale is SQL_Latin1_General_CP1_CI_AS<br />
it could be a problem since you often will run into error when execution of the SQL code across different databases will return Collation error.</p>
<p>Too late? Not exactly.</p>
<p>In many cases your solution would be to adjust Collation setting for the database using to following code:</p>
<pre class="brush: sql;">ALTER DATABASE DatabaseName COLLATE SQL_Latin1_General_CP1_CI_AS</pre>
<p>Problem would still exist though, any new database created will get default Collation setting from &#8230; MASTER database for your SQL Server Instance.</p>
<p> And here some hoops will be required. Following steps will help you overcome the issue:</p>
<ol>
<li>Detach all your user databases</li>
<li>Stop your SQL Server</li>
<li>In <strong>C:\Program Files\Microsoft SQL Server\80\Tools\Binn\</strong> folder locate <strong>rebuildm.exe</strong> and run it. This utility which comes with SQL Server (you will need to have client tools to be installed) allows you to repair your master database from original installation CD/DVD/Folder and also change default Collation Setting for your SQL Server instance. Go to Settings and choose appropriate collation designator or SQL Collation.<br />
If you cannot find rebuildm.exe, it means you are using SQL Server 2005 or 2008. Then the following may help:<br />
<a href="http://msdn.microsoft.com/en-us/library/ms144259(SQL.90).aspx" target="_blank">for SQL Server 2005</a></p>
<pre class="brush: plain;">
start /wait &lt;CD or DVD Drive&gt;\setup.exe /qn INSTANCENAME=&lt;InstanceName&gt; REINSTALL=SQL_Engine REBUILDDATABASE=1 SAPWD=&lt;NewStrongPassword&gt;</pre>
<p><a href="http://blogs.msdn.com/psssql/archive/2008/08/29/how-to-rebuild-system-databases-in-sql-server-2008.aspx" target="_blank">for SQL Server 2008</a></p>
<pre class="brush: plain;">
setup.exe  /QUIET  /ACTION=REBUILDDATABASE  /INSTANCENAME=instance_name  /SQLSYSADMINACCOUNTS= accounts   [/SAPWD=password]
</pre>
</li>
<li>Rebuild your master database</li>
<li>Reattach your user databases</li>
<li>Check that collation for master and user databases is a desired using first query above.</li>
</ol>
<p>This is much easier then to recreate a SQL Server instance from scratch.</p>
<p><strong>Note. </strong>There is less safe way of getting the same result &#8211; adjust Windows Registry.<br />
Your default collation name is stored under</p>
<pre class="brush: sql;">HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSSQLServer\MSSQLServer\
DefaultCollationName</pre>
<hr/><span style="font-size: 7pt">Copyright &copy; 2010 <strong><a href="http://blog.dragonsoft.us">Serge&#039;s Technology View</a></strong>. This Feed is for personal non-commercial use only.</span>]]></content:encoded>
			<wfw:commentRss>http://blog.dragonsoft.us/2008/04/15/sql-server-collation-an-enemy-or-a-friend/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Load text file data into SQL Server table</title>
		<link>http://blog.dragonsoft.us/2008/03/06/load-text-file-data-into-sql-server-table/</link>
		<comments>http://blog.dragonsoft.us/2008/03/06/load-text-file-data-into-sql-server-table/#comments</comments>
		<pubDate>Thu, 06 Mar 2008 17:36:40 +0000</pubDate>
		<dc:creator>Serguei Dosyukov</dc:creator>
				<category><![CDATA[Fun stuff with SQL Server]]></category>
		<category><![CDATA[import csv]]></category>
		<category><![CDATA[import text file]]></category>
		<category><![CDATA[sql server]]></category>

		<guid isPermaLink="false">http://blog.dragonsoft.us/2008/03/06/load-text-file-data-into-sql-server-table/</guid>
		<description><![CDATA[Last time we have seen how to manipulate text files from SQL Server code using Scripting object. This time we would look at &#8220;Read File As Table&#8221; operation from a different angle &#8211; using BULK INSERT operation. There are pros and cons in this approach. Lets look at them. Advantages: Getting data in table format, with [...]]]></description>
			<content:encoded><![CDATA[<p>Last time we have seen how to <a href="http://blog.dragonsoft.us/2008/02/15/sql-manage-files-from-inside-sql-code/">manipulate text files from SQL Server</a> code using Scripting object.</p>
<p>This time we would look at &#8220;<strong>Read File As Table</strong>&#8221; operation from a different angle &#8211; using BULK INSERT operation.</p>
<p>There are pros and cons in this approach. Lets look at them.</p>
<p>Advantages:</p>
<ul>
<li>Getting data in table format, with properly associated columns</li>
<li>BULK INSERT is quicker operation if you know what you are importing</li>
<li>IDENTITY INSERT and other Batch optimizers</li>
<li>Transaction support</li>
<li>Is easiest way to copy data between servers</li>
</ul>
<p>Disadvantages:</p>
<ul>
<li>it is supported for variation of CSV formatted files only</li>
<li>structure of the file is strict and small error in formatting or a hidden character can cause problems with import</li>
<li>only members of the <strong>sysadmin</strong> and <strong>bulkadmin</strong> server roles can perform an operation</li>
<li>could be messy if not properly managed.</li>
</ul>
<p>All saying, you should always try and see if it works for you, instead of creating custom import procedures or using DTS functionality.</p>
<p>Let fun begins:</p>
<p>We would be working with the following table:</p>
<pre class="brush: sql;">CREATE TABLE StoreList (
StoreID INT,
StoreName VARCHAR(32),
  City VARCHAR(32),
  State VARCHAR(2),
  Country VARCHAR(32)
)</pre>
<p>Sample data we would be using is stored in CSV file called c:\stores.csv</p>
<pre>1111,Stone Age Books,Boston,MA,USA
2222,Harley &amp; Davidson,Washington,DC,USA
3333,Infodata Algosystems,Berkeley,CA,USA</pre>
<p>When table is created Bulk insert could be performed using the following command:</p>
<pre class="brush: sql;">BULK INSERT dbo.StoreList FROM 'c:\stores.csv' WITH (
   FIELDTERMINATOR = ',',
   ROWTERMINATOR = '\n'
)
</pre>
<p>Notice that we are using coma as separator, it might not be appropriate in some situations and could be easily addressed for let say TAB-separated values using</p>
<pre class="brush: sql;">BULK INSERT dbo.StoreList FROM 'c:\stores.csv'
WITH (
   ROWTERMINATOR = '\n'
)</pre>
<p>As you can see that FIELDTERMINATOR has been removed. This is a case because &#8216;\t&#8217; value otherwise used here is a default for the parameter. You can adjust Field and Row terminators to better suite format present in the file in each case.</p>
<p>Another thing to remember that some of the files, especially results from Excel export might include header rows which might make your import fail with conversion error</p>
<blockquote><p>Bulk insert data conversion error (type mismatch) for&#8230;</p></blockquote>
<p>To address the issue simply exclude header related rows from import</p>
<pre class="brush: sql;">BULK INSERT dbo.StoreList FROM 'c:\stores.csv'
WITH (
    FIRSTROW = 2,
    ROWTERMINATOR = '\n'
)
</pre>
<p>There are other settings which might affect bulk import:</p>
<ul>
<li>Turning Insert Triggers On while performing import</li>
<li>Keep NULL values &#8211; situation when there is nothing specified between delimiters</li>
<li>specifying LASTROW of the file to import</li>
<li>how many error to ignore when found in the file before invalidating a whole import</li>
</ul>
<p>Please refer to SQL Server Book Online for details about such settings.</p>
<hr/><span style="font-size: 7pt">Copyright &copy; 2010 <strong><a href="http://blog.dragonsoft.us">Serge&#039;s Technology View</a></strong>. This Feed is for personal non-commercial use only.</span>]]></content:encoded>
			<wfw:commentRss>http://blog.dragonsoft.us/2008/03/06/load-text-file-data-into-sql-server-table/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>File management from inside SQL code</title>
		<link>http://blog.dragonsoft.us/2008/02/15/sql-manage-files-from-inside-sql-code/</link>
		<comments>http://blog.dragonsoft.us/2008/02/15/sql-manage-files-from-inside-sql-code/#comments</comments>
		<pubDate>Fri, 15 Feb 2008 20:28:35 +0000</pubDate>
		<dc:creator>Serguei Dosyukov</dc:creator>
				<category><![CDATA[Delphi]]></category>
		<category><![CDATA[Fun stuff with SQL Server]]></category>
		<category><![CDATA[file management]]></category>
		<category><![CDATA[sql]]></category>
		<category><![CDATA[sql server]]></category>

		<guid isPermaLink="false">http://blog.dragonsoft.us/2008/02/15/sql-manage-files-from-inside-sql-code/</guid>
		<description><![CDATA[Writing a log, dumping data, looking for file to be used in Bulk insert&#8230; There are many situations when you would want to have access to files from inside your SQL code on Microsoft SQL Server. Did you know that you actually can do this? No? Check below for code snippets to perform various operations on files. [...]]]></description>
			<content:encoded><![CDATA[<p>Writing a log, dumping data, looking for file to be used in Bulk insert&#8230;</p>
<p>There are many situations when you would want to have access to files from inside your SQL code on Microsoft SQL Server.</p>
<p>Did you know that you actually can do this? No? Check below for code snippets to perform various operations on files. It is presented in form of the functions but you are actually not limited to that</p>
<p><strong>Prerequisites and assumptions</strong></p>
<ol>
<li>Your script should have sufficient rights to perform required access to files (not necessarily local).</li>
<li><em>Scripting.FileSystemObject </em>should be present at your SQL Server location and accessible.</li>
</ol>
<p><strong>Check if file exists</strong><br />
<span id="more-144"></span></p>
<pre class="brush: sql;">
CREATE FUNCTION [dbo].[ufn_IsFileExists] (
@FilePath VARCHAR(255)
)
RETURNS INT
AS
BEGIN
DECLARE
  @objFileSystem int,
  @hr int,
  @i int
EXEC @hr = sp_OACreate 'Scripting.FileSystemObject', @objFileSystem out
IF @HR = 0
BEGIN
  EXEC sp_OAMethod @objFileSystem, 'FileExists', @i out, @FilePath
  EXEC sp_OADestroy @objFileSystem
END
ELSE
BEGIN
  SET @i = -1
END
RETURN @i
END
</pre>
<p><strong>Write string into file</strong></p>
<pre class="brush: sql;">
CREATE FUNCTION [dbo].[ufn_WriteStringToFile] (
  @CreateFile int,
  @FilePath varchar(500),
  @String varchar(4000) )
RETURNS varchar(200)
AS
BEGIN
DECLARE
  @objFileSystem int,
  @objTextStream int,
  @objErrorObject int,
  @strErrorMsg varchar(1000),
  @Command varchar(1000),
  @HR int,
  @fileAndPath varchar(80)
SET @strErrorMsg = 'opening the File System Object'
EXEC @hr = sp_OACreate 'Scripting.FileSystemObject' , @objFileSystem OUT
IF @HR = 0
BEGIN
  SET @objErrorObject = @objFileSystem
  IF (@CreateFile = 1)
  BEGIN
SET @strErrorMsg= 'Creating file &quot;' + @FilePath + '&quot;'
EXEC @hr = sp_OAMethod @objFileSystem, 'OpenTextFile', @objTextStream OUT, @FilePath, 2, True
  END
  ELSE
  BEGIN
  SET @strErrorMsg = 'Opening file &quot;' + @FilePath + '&quot;'
  EXEC @hr = sp_OAMethod @objFileSystem, 'OpenTextFile', @objTextStream OUT, @FilePath, 8, True
  END
END
IF @HR = 0
BEGIN
  SET @objErrorObject = @objTextStream
  SET @strErrorMsg = 'Writing to the file &quot;' + @FilePath + '&quot;'
  EXEC @hr = sp_OAMethod @objTextStream, 'WriteLine', Null, @String
END
IF @HR=0
BEGIN
  SET @objErrorObject = @objTextStream
  SET @strErrorMsg = 'Closing the file &quot;' + @FileAndPath + '&quot;'
  EXEC @hr = sp_OAMethod @objTextStream, 'Close'
END
IF @HR &lt;&gt; 0
BEGIN
  DECLARE
  @Source varchar(255),
  @Description varchar(255),
  @Helpfile varchar(255),
  @HelpID int
EXEC sp_OAGetErrorInfo @objErrorObject, @Source OUTPUT, @Description OUTPUT, @Helpfile OUTPUT, @HelpID OUTPUT
  SET @strErrorMsg = 'Error: ' + coalesce(@strErrorMsg, 'Unknown') + ', ' + coalesce(@Description, '')
END
EXEC sp_OADestroy @objTextStream
RETURN @strErrorMsg
END
</pre>
<p><strong>Read File As Table</strong></p>
<pre class="brush: sql;">
CREATE FUNCTION [dbo].[ufn_ReadFileAsTable] (
@FilePath VARCHAR(255)
)
RETURNS @File TABLE ([LineNo] int identity(1,1), [Line] varchar(8000))
AS
BEGIN
DECLARE
@objFileSystem int,
@objTextStream int,
@objErrorObject int,
@strErrorMsg varchar(1000),
  @hr int,
  @String VARCHAR(8000),
@YesOrNo INT
SET @strErrorMsg = 'opening the File System Object'
EXEC @hr = sp_OACreate 'Scripting.FileSystemObject', @objFileSystem OUT
IF @HR=0
BEGIN
SET @objErrorObject = @objFileSystem
SET @strErrorMsg = 'Opening file &quot;' + @FilePath + '&quot;'
--Open for reading, FormatASCII
EXEC @HR = sp_OAMethod @objFileSystem, 'OpenTextFile', @objTextStream OUT, @FilePath, 1, False, 0
END
WHILE @HR = 0
BEGIN
  IF @HR=0
  BEGIN
SET @objErrorObject = @objTextStream
SET @strErrorMsg = 'Check if there is more to read in &quot;' + @FilePath + '&quot;'
EXEC @HR = sp_OAGetProperty @objTextStream, 'AtEndOfStream', @YesOrNo OUTPUT
IF @YesOrNo &lt;&gt; 0 BREAK
  END
  IF @HR=0
  BEGIN
SET @objErrorObject = @objTextStream
SET @strErrorMsg = 'Reading from the output file &quot;' + @FilePath + '&quot;'
EXEC @HR = sp_OAMethod @objTextStream, 'Readline', @String OUTPUT
    INSERT INTO @file(line) SELECT @String
  END
END
IF @HR=0
BEGIN
SET @objErrorObject = @objTextStream
SET @strErrorMsg = 'Closing the output file &quot;' + @FilePath + '&quot;'
EXEC @HR = sp_OAMethod @objTextStream, 'Close'
END
IF @hr &lt;&gt; 0
BEGIN
  DECLARE
@Source varchar(255),
@Description varchar(255),
@Helpfile varchar(255),
@HelpID int
EXEC sp_OAGetErrorInfo @objErrorObject, @Source OUTPUT, @Description OUTPUT, @Helpfile OUTPUT, @HelpID OUTPUT
SET @strErrorMsg = 'Error: ' + coalesce(@strErrorMsg, 'Unknown') + ', ' + coalesce(@Description, '')
INSERT INTO @File(line) select @strErrorMsg
END
EXEC sp_OADestroy @objTextStream
-- Fill the table variable with the rows for your result set
RETURN
END
</pre>
<p>Enjoy.</p>
<hr/><span style="font-size: 7pt">Copyright &copy; 2010 <strong><a href="http://blog.dragonsoft.us">Serge&#039;s Technology View</a></strong>. This Feed is for personal non-commercial use only.</span>]]></content:encoded>
			<wfw:commentRss>http://blog.dragonsoft.us/2008/02/15/sql-manage-files-from-inside-sql-code/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>SQL date operations: First day, Last day of the month&#8230;</title>
		<link>http://blog.dragonsoft.us/2008/02/05/first-day-last-day-of-the-month-and-sql/</link>
		<comments>http://blog.dragonsoft.us/2008/02/05/first-day-last-day-of-the-month-and-sql/#comments</comments>
		<pubDate>Tue, 05 Feb 2008 16:56:14 +0000</pubDate>
		<dc:creator>Serguei Dosyukov</dc:creator>
				<category><![CDATA[Fun stuff with SQL Server]]></category>
		<category><![CDATA[date manipulations]]></category>
		<category><![CDATA[piclens]]></category>
		<category><![CDATA[sql]]></category>
		<category><![CDATA[sql server]]></category>

		<guid isPermaLink="false">http://blog.dragonsoftru.com/2007/01/18/first-day-last-day-of-the-month-and-sql/</guid>
		<description><![CDATA[Did you ever faced a situation when you need quickly calculate some boundaries of the Date value like First Day of the month, Last Day of the month, etc&#8230; in T-SQL? Colegue of mine asked me this question&#8230; WOW! What do you know&#8230; It is actually very easy if we think about it for a second&#8230; [...]]]></description>
			<content:encoded><![CDATA[<p>Did you ever faced a situation when you need quickly calculate some boundaries of the Date value like First Day of the month, Last Day of the month, etc&#8230; in T-SQL?</p>
<p>Colegue of mine asked me this question&#8230; WOW! What do you know&#8230;<br />
It is actually very easy if we think about it for a second&#8230;</p>
<p>So lets fun begin&#8230;</p>
<pre class="brush: sql;">--First Day of the Current Month:
select DATEADD(mm, DATEDIFF(mm, 0, GETDATE()), 0)

-- Last Day of the Current Month:
select DATEADD(ms, -3, DATEADD(mm, DATEDIFF(m, 0, GETDATE()) + 1, 0))

-- Last Day of Prior Month:
select DATEADD(ms, -3, DATEADD(mm, DATEDIFF(mm, 0, GETDATE()), 0))

-- First Day of the Current Year:
select DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0)

-- Last Day of the Current Year:
select DATEADD(ms, -3, DATEADD(yy, DATEDIFF(yy, 0, GETDATE()) + 1, 0))

-- Last Day of Prior Year:
select DATEADD(ms, -3, DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0))
</pre>
<p>And some more&#8230;</p>
<pre class="brush: sql;">-- First Day of the Quarter:
select DATEADD(qq, DATEDIFF(qq, 0, GETDATE()), 0)

-- Monday of the Current Week:
select DATEADD(wk, DATEDIFF(wk, 0, GETDATE()), 0)

-- Midnight for the Current Day:
select DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), 0)

-- First Monday of the Month:
select DATEADD(wk, DATEDIFF(wk, 0, DATEADD(dd, 6 - DATEPART(day, GETDATE()), GETDATE())), 0)

-- Last 2 full months
select DATEADD(ms, -3, DATEADD(mm, DATEDIFF(mm, 0, GETDATE()) - 2, 0))
</pre>
<hr/><span style="font-size: 7pt">Copyright &copy; 2010 <strong><a href="http://blog.dragonsoft.us">Serge&#039;s Technology View</a></strong>. This Feed is for personal non-commercial use only.</span>]]></content:encoded>
			<wfw:commentRss>http://blog.dragonsoft.us/2008/02/05/first-day-last-day-of-the-month-and-sql/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
