<?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>Code Corner &#187; SQL</title>
	<atom:link href="http://CodeCorner.galanter.net/category/sql/feed/" rel="self" type="application/rss+xml" />
	<link>http://CodeCorner.galanter.net</link>
	<description>ASP.NET, XML, SQL and Javascript tips and tricks</description>
	<lastBuildDate>Sun, 19 Feb 2012 03:04:04 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>@@ROWCOUNT is affected by IF statement</title>
		<link>http://CodeCorner.galanter.net/2012/01/19/rownumber-is-affected-by-if-statement/</link>
		<comments>http://CodeCorner.galanter.net/2012/01/19/rownumber-is-affected-by-if-statement/#comments</comments>
		<pubDate>Thu, 19 Jan 2012 20:03:19 +0000</pubDate>
		<dc:creator>Yuriy</dc:creator>
				<category><![CDATA[SQL]]></category>
		<category><![CDATA[Data]]></category>
		<category><![CDATA[Quick fix]]></category>
		<category><![CDATA[solution]]></category>
		<category><![CDATA[workaround]]></category>

		<guid isPermaLink="false">http://CodeCorner.galanter.net/?p=1629</guid>
		<description><![CDATA[Let&#8217;s say you&#8217;re writing T-SQL code and need to make sure that your query returns one and only row. If no records returned &#8211; an error message needs to be shown. If more than one record is returned &#8211; another error message needs to be show. The code goes something like this: Now if your [...]]]></description>
			<content:encoded><![CDATA[<p>Let&#8217;s say you&#8217;re writing T-SQL code and need to make sure that your query returns one and only row. If no records returned &#8211; an error message needs to be shown. If more than one record is returned &#8211; another error message needs to be show. The code goes something like this:</p>
<pre class="brush: sql; title: ; notranslate">-- ... query runs here and returns row

IF @@ROWCOUNT = 0 RAISERROR('No records found', 18, 1)
ELSE IF @@ROWCOUNT &gt; 0 RAISERROR('More than one record found', 18, 1)

-- ... continue when exactly one row is returned</pre>
<p>Now if your query returns 3 records you&#8217;d expect it to trip the second IF statement and raise error with correct message. Unfortunately this doesn&#8217;t happen. The reason being &#8211; the first IF statement resets @@ROWCOUNT to 0. So, to avoid this we need to preserve the @@ROWCOUNT value in a local variable:</p>
<pre class="brush: sql; title: ; notranslate">DECLARE @iRowCount int

-- ... query runs here and returns row

SET @iRowCount = @@ROWCOUNT

IF @iRowCount = 0 RAISERROR('No records found', 18, 1)
ELSE IF @iRowCount &gt; 0 RAISERROR('More than one record found', 18, 1)

-- ... continue when exactly one row is returned</pre>
<p>This way count of rows returned by the query is saved and is not affected by any following statements.</p>
<div id="crp_related"><h4>Related Posts:</h4><ul><li><a href="http://CodeCorner.galanter.net/2011/04/22/solution-for-previoussibling-is-null-or-not-an-object-error-in-grouped-ultrawebgrid/" rel="bookmark" class="crp_title">Solution for &#8216;previousSibling&#8217; is null or not an object error in grouped UltraWebGrid</a></li><li><a href="http://CodeCorner.galanter.net/2008/05/07/dynamic-number-of-fields-in-a-query-for-ssrs-2005/" rel="bookmark" class="crp_title">Dynamic number of fields in a query for SSRS 2005</a></li></ul></div>]]></content:encoded>
			<wfw:commentRss>http://CodeCorner.galanter.net/2012/01/19/rownumber-is-affected-by-if-statement/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>TSQL: Filling missing date range</title>
		<link>http://CodeCorner.galanter.net/2011/08/29/tsql-filling-missing-date-range/</link>
		<comments>http://CodeCorner.galanter.net/2011/08/29/tsql-filling-missing-date-range/#comments</comments>
		<pubDate>Mon, 29 Aug 2011 21:47:00 +0000</pubDate>
		<dc:creator>Yuriy</dc:creator>
				<category><![CDATA[SQL]]></category>
		<category><![CDATA[cool]]></category>
		<category><![CDATA[Data]]></category>
		<category><![CDATA[solution]]></category>

		<guid isPermaLink="false">http://CodeCorner.galanter.net/?p=1388</guid>
		<description><![CDATA[Let&#8217;s say you have a table with some dates and numeric values e.g.: As you can see not all dates are in the sequential order, 24th comes after 22nd etc. But in many cases you need this data to be sequential, for example if this data feeds a chart you need to fill it with [...]]]></description>
			<content:encoded><![CDATA[<p>Let&#8217;s say you have a table with some dates and numeric values e.g.:</p>
<pre class="brush: plain; title: ; notranslate">2011-08-19	16
2011-08-22	45
2011-08-24	62
2011-08-25	88
2011-08-27	17
2011-08-28	35
2011-09-01	10
2011-09-02	79
2011-09-03	70
2011-09-07	83</pre>
<p>As you can see not all dates are in the sequential order, 24th comes after 22nd etc. But in many cases you need this data to be sequential, for example if this data feeds a chart you need to fill it with missing dates and 0 for a value. There is an easy way to achieve this.<span id="more-1388"></span></p>
<p>Some solution suggest creation of a Calendar table &#8211; table with prefilled dates and values, but for this task it would be an overkill. A small Common Table Expression will suffice instead.</p>
<p>Let&#8217;s say your table with data is called <strong>#TEMP_DATA</strong>, column with dates is called <strong>MyDate</strong>, column with integer values is called <strong>MyValue</strong>. Consider following CTE:</p>
<pre class="brush: sql; title: ; notranslate">-- Getting date limits
DECLARE @MaxDate DateTime
DECLARE @MinDate DateTime

SELECT @MaxDate = MAX(MyDate), @MinDate = MIN(MyDate) FROM #TEMP_DATA;

-- Calendar CTE with ALL the dates
WITH mycte AS
    (
        SELECT @MinDate AS DateValue
        UNION ALL
        SELECT DateValue + 1
        FROM mycte
        WHERE DateValue + 1 &lt;= @MaxDate
    )
SELECT DateValue, 0 AS IntValue
FROM mycte
OPTION (MAXRECURSION 0)</pre>
<p>It will produce full date range within limits specified by dates in <strong>#TEMP_DATA</strong> table:</p>
<pre class="brush: plain; title: ; notranslate">2011-08-19 	0
2011-08-20 	0
2011-08-21 	0
2011-08-22 	0
2011-08-23 	0
2011-08-24 	0
2011-08-25 	0
2011-08-26 	0
2011-08-27 	0
2011-08-28 	0
2011-08-29 	0
2011-08-30 	0
2011-08-31 	0
2011-09-01 	0
2011-09-02 	0
2011-09-03 	0
2011-09-04 	0
2011-09-05 	0
2011-09-06 	0
2011-09-07 	0</pre>
<p>Only thing remains is to marry it in happy UNION to original table with data:</p>
<pre class="brush: sql; title: ; notranslate">DECLARE @MaxDate DateTime
DECLARE @MinDate DateTime

SELECT @MaxDate = MAX(MyDate), @MinDate = MIN(MyDate) FROM #TEMP_DATA;

-- Calendar CTE with ALL the dates
WITH mycte as
    (
        SELECT @MinDate AS DateValue
        UNION ALL
        SELECT DateValue + 1
        FROM mycte
        WHERE DateValue + 1 &lt;= @MaxDate
    )
-- Original data
SELECT MyDate, MyValue FROM #TEMP_DATA
UNION
-- Filled in data
SELECT DateValue, 0
FROM mycte LEFT JOIN #TEMP_DATA ON DateValue = MyDate WHERE MyDate IS NULL
ORDER BY 1
OPTION (MAXRECURSION 0)</pre>
<p>Query selects original data that has dates missing and then UNIONs it with full date range from the CTE which is limited only to missing dates by LEFT JOIN. The result is perfect combination:</p>
<pre class="brush: plain; title: ; notranslate">2011-08-19	16
2011-08-20	0
2011-08-21	0
2011-08-22	45
2011-08-23	0
2011-08-24	62
2011-08-25	88
2011-08-26	0
2011-08-27	17
2011-08-28	35
2011-08-29	0
2011-08-30	0
2011-08-31	0
2011-09-01	10
2011-09-02	79
2011-09-03	70
2011-09-04	0
2011-09-05	0
2011-09-06	0
2011-09-07	83</pre>
<p>All the dates are in sequential order, original date range is preserved and missing values are filled with zeroes.</p>
<div id="crp_related"><h4>Related Posts:</h4><ul><li><a href="http://CodeCorner.galanter.net/2011/06/14/stored-procedure-in-linq2sql-query/" rel="bookmark" class="crp_title">Stored Procedure in LINQ2SQL query</a></li><li><a href="http://CodeCorner.galanter.net/2011/08/18/changing-hosting-again-and-again/" rel="bookmark" class="crp_title">Changing Hosting. Again and again.</a></li></ul></div>]]></content:encoded>
			<wfw:commentRss>http://CodeCorner.galanter.net/2011/08/29/tsql-filling-missing-date-range/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Elusive &#8220;String or binary data would be truncated&#8221; error</title>
		<link>http://CodeCorner.galanter.net/2011/08/19/elusive-string-or-binary-data-would-be-truncated-error/</link>
		<comments>http://CodeCorner.galanter.net/2011/08/19/elusive-string-or-binary-data-would-be-truncated-error/#comments</comments>
		<pubDate>Fri, 19 Aug 2011 18:11:27 +0000</pubDate>
		<dc:creator>Yuriy</dc:creator>
				<category><![CDATA[SQL]]></category>
		<category><![CDATA[bug]]></category>
		<category><![CDATA[workaround]]></category>

		<guid isPermaLink="false">http://CodeCorner.galanter.net/?p=1382</guid>
		<description><![CDATA[This was driving me nuts. I have a very basic SQL code similar to I was getting error &#8220;String or binary data would be truncated&#8221;, but only when 2 conditions were met: @val1 is quite large Either SQL Server/computer just restarted or stored procedure Proc2 was just updated (ALTER) Error happened just by the fact [...]]]></description>
			<content:encoded><![CDATA[<p>This was driving me nuts. I have a very basic SQL code similar to</p>
<pre class="brush: sql; title: ; notranslate">ALTER PROCEDURE Proc1(@val1 NVARCHAR(max))
AS
BEGIN
    -- some code
    EXEC Proc2 @val2 = @val1
    -- some other code
END</pre>
<p>I was getting error <span style="color: #ff0000;">&#8220;String or binary data would be truncated&#8221;</span>, but only when 2 conditions were met:</p>
<ol>
<li><strong>@val1</strong> is quite large</li>
<li>Either SQL Server/computer just restarted or stored procedure <strong>Proc2</strong> was just updated (ALTER)</li>
</ol>
<p>Error happened  just by the fact of the <strong>EXEC Proc2</strong> being there it didn&#8217;t even had to do anything, it could RETURN straight away. Both <strong>@val2</strong> an <strong>@val1</strong> are of a type <strong>NVARCHAR(max)</strong> so there is no reason for the error. The error happened only once, after that I can pass data of any size &#8211; and no error would happen. Like I said &#8211; nuts.<span id="more-1382"></span></p>
<p>Maybe it&#8217;s a bug in SQL Server &#8211; it doesn&#8217;t expect such a large value from start, maybe I am doing something wrong. The solution I came up with is kinda weird, but it works: On the very fist call to <strong>Proc1</strong> I pass a very small predefined value for <strong>@val1</strong> parameter, something like <em>!TEST!</em>. The call goes without any error and and all consecutive calls with any data size as well. The only thing <strong>Proc2</strong> has to detect that <em>!TEST!</em> value is passed and don&#8217;t do any actual work with it, just RETURN straight back</p>
<div id="crp_related"><h4>Related Posts:</h4><ul><li><a href="http://CodeCorner.galanter.net/2009/04/03/tsql-isnumeric-function-returns-false-positives/" rel="bookmark" class="crp_title">TSQL IsNumeric function returns false positives</a></li><li><a href="http://CodeCorner.galanter.net/2008/08/21/infragistics-ultrawebgrid-grouping-in-code-problem-solved/" rel="bookmark" class="crp_title">Infragistics UltraWebGrid grouping in code problem (solved)</a></li></ul></div>]]></content:encoded>
			<wfw:commentRss>http://CodeCorner.galanter.net/2011/08/19/elusive-string-or-binary-data-would-be-truncated-error/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>SQL Server stored procedure runs slow from .NET code</title>
		<link>http://CodeCorner.galanter.net/2011/08/05/sql-server-stored-procedure-runs-slow-from-net-code/</link>
		<comments>http://CodeCorner.galanter.net/2011/08/05/sql-server-stored-procedure-runs-slow-from-net-code/#comments</comments>
		<pubDate>Fri, 05 Aug 2011 18:58:54 +0000</pubDate>
		<dc:creator>Yuriy</dc:creator>
				<category><![CDATA[ADO.NET]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[Data]]></category>
		<category><![CDATA[slow]]></category>
		<category><![CDATA[solution]]></category>
		<category><![CDATA[speed]]></category>

		<guid isPermaLink="false">http://CodeCorner.galanter.net/?p=1365</guid>
		<description><![CDATA[This has probably been discussed a lot before, but just in case here it is again, possible solution for following scenario: You&#8217;re calling SQL Server stored procedure from your .NET code and it runs extremely slow. When you run same SP with exactly the same parameters (as captured by SQL Server Profiler) directly in SQL [...]]]></description>
			<content:encoded><![CDATA[<p>This has probably been discussed a lot before, but just in case here it is again, possible solution for following scenario:</p>
<p><em>You&#8217;re calling SQL Server stored procedure from your .NET code and it runs extremely slow. When you run same SP with exactly the same parameters (as captured by SQL Server Profiler) directly in SQL Server Management Studio, it runs very fast. What gives?</em></p>
<p>Chances are &#8211; that SP was executed before and query plan was cached for the specific parameters. To avoid this add <strong>WITH RECOMPILE</strong> option to your <strong>CREATE PROCEDURE</strong> or <strong>ALTER PROCEDURE</strong> statement. This will force SQL Server to create a new query plan every time SP runs, perhaps adding slight overhead, but creating an optimized path that will cover that overhead tenfold.</p>
<div id="crp_related"><h4>Related Posts:</h4><ul><li><a href="http://CodeCorner.galanter.net/2011/04/29/ssrs-how-to-implement-build-in-parameter-based-on-external-parameter-passed-from-reportviewer/" rel="bookmark" class="crp_title">SSRS: How to implement build-in parameter based on external parameter passed from ReportViewer</a></li><li><a href="http://CodeCorner.galanter.net/2011/06/14/stored-procedure-in-linq2sql-query/" rel="bookmark" class="crp_title">Stored Procedure in LINQ2SQL query</a></li></ul></div>]]></content:encoded>
			<wfw:commentRss>http://CodeCorner.galanter.net/2011/08/05/sql-server-stored-procedure-runs-slow-from-net-code/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Solution for &#8220;OraOLEDB.Oracle Provider is not registered&#8221; error</title>
		<link>http://CodeCorner.galanter.net/2011/07/27/solution-for-oraoledb-oracle-provider-is-not-registered-error/</link>
		<comments>http://CodeCorner.galanter.net/2011/07/27/solution-for-oraoledb-oracle-provider-is-not-registered-error/#comments</comments>
		<pubDate>Wed, 27 Jul 2011 20:40:53 +0000</pubDate>
		<dc:creator>Yuriy</dc:creator>
				<category><![CDATA[Rant]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[bug]]></category>
		<category><![CDATA[Oracle]]></category>
		<category><![CDATA[solution]]></category>

		<guid isPermaLink="false">http://CodeCorner.galanter.net/?p=1355</guid>
		<description><![CDATA[While connecting from an ASP.NET application to an Oracle database via OLEDB I got following error: OraOLEDB.Oracle Provider is not registered on the local machine Now I know that the driver was installed and registered. I downloaded an official driver from Oracle WebSite. In my case it was ODAC112021Xcopy_x64.zip 64-bit version for XCopy deployment. It [...]]]></description>
			<content:encoded><![CDATA[<p>While connecting from an ASP.NET application to an Oracle database via OLEDB I got following error:</p>
<p><strong><span style="color: #ff0000;">OraOLEDB.Oracle Provider is not registered on the local machine</span></strong></p>
<p>Now I know that the driver was installed and registered. I downloaded an official driver from Oracle WebSite. In my case it was <strong>ODAC112021Xcopy_x64.zip</strong> 64-bit version for XCopy deployment. It installs in 2 easy steps:</p>
<ol>
<li>Unzip downloaded file into any folder</li>
<li>Run (as administrator) command: <strong>INSTALL <em>TYPE PATH NAME DEPENDANCIES</em></strong></li>
</ol>
<p>Where
<ul>
<li><em>TYPE</em> &#8211; type of installation (e.g. OLEDB, basic etc.)</li>
<li><em>Path</em> &#8211; where you want driver installed</li>
<li><em>Name</em> &#8211; Oracle home name</li>
<li><em>Dependencies</em> &#8211; true/false whether to install dependencies (e.g. instant client)</li>
</ul>
<p>So my command was</p>
<p><strong><span style="color: blue;">INSTALL ALL &#8220;C:\Program Files\Oracle64Driver&#8221; Oracle64Driver TRUE</span></strong></p>
<p>Which copied the files and created correct Registry entries (I checked). And still I was getting the error. I Googled it (a lot) but majority of suggestions was that the error is due to Windows ACL and correct permissions should be set on the driver folder. Didn&#8217;t help me.</p>
<p>So I fired up trusted ProcessMonitor and it showed that <strong>W3WP.EXE</strong> (ASP.NET process) was trying to access missing <strong>OCI.DLL</strong> file in the path <strong>C:\Program Files\Oracle64Driver\Bin</strong>, e.g. in the Bin folder of the path were the driver was installed. Looking back at the place were I unzipped the original driver files I found that DLL inside of &#8220;instantclient&#8221; folder. So I copied entire content of that folder into Bin folder at the destination. And Voila! The error disappeared.</p>
<p>Apparently Instant Client files aren&#8217;t copied by the installer even when Dependencies option is set to true. </p>
<div id="crp_related"><h4>Related Posts:</h4><ul><li><a href="http://CodeCorner.galanter.net/2011/08/24/solution-for-asp-net-access-to-temporary-folder-denied-error/" rel="bookmark" class="crp_title">Solution for ASP.NET access to temporary folder denied error</a></li><li><a href="http://CodeCorner.galanter.net/2011/08/19/use-symlinks-to-serve-subdomain-content/" rel="bookmark" class="crp_title">Use symlinks to serve subdomain content</a></li></ul></div>]]></content:encoded>
			<wfw:commentRss>http://CodeCorner.galanter.net/2011/07/27/solution-for-oraoledb-oracle-provider-is-not-registered-error/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Stored Procedure in LINQ2SQL query</title>
		<link>http://CodeCorner.galanter.net/2011/06/14/stored-procedure-in-linq2sql-query/</link>
		<comments>http://CodeCorner.galanter.net/2011/06/14/stored-procedure-in-linq2sql-query/#comments</comments>
		<pubDate>Tue, 14 Jun 2011 15:43:47 +0000</pubDate>
		<dc:creator>Yuriy</dc:creator>
				<category><![CDATA[SQL]]></category>
		<category><![CDATA[VB.NET]]></category>
		<category><![CDATA[Error]]></category>
		<category><![CDATA[linq]]></category>
		<category><![CDATA[solution]]></category>

		<guid isPermaLink="false">http://CodeCorner.galanter.net/?p=1336</guid>
		<description><![CDATA[Linq2Sql has a great use of stored procedures &#8211; it converts them into methods which you can easily call using standardized .NET syntax. For example if you have SP: after dragging it into Linq2Sql designer you can call it in your .NET code like this: but there are 2 caveats. If you plan to use [...]]]></description>
			<content:encoded><![CDATA[<p>Linq2Sql has a great use of stored procedures &#8211; it converts them into methods which you can easily call using standardized .NET syntax. For example if you have SP:</p>
<pre class="brush: sql; title: ; notranslate">ALTER PROCEDURE MyProcedure(MyParam int) ...</pre>
<p>after dragging it into Linq2Sql designer you can call it in your .NET code like this:</p>
<pre class="brush: vb; title: ; notranslate">Dim aResults = MyDbContext.MyProcedure(2011)</pre>
<p>but there are 2 caveats.<span id="more-1336"></span></p>
<ol>
<li>If you plan to use stored procedure in a Linq2Sql query &#8211; <strong>do not use temp tables</strong>. It confuses ORM, it cannot determine type of output result and you will get a warning:
<p><strong style='color:red'><em>The return types for the following stored procedures could not be detected</em></strong></p>
<p>If you need to store temporary data somewhere &#8211; use table variables instead.</li>
<li>If you use code above as is and then attempt to use query variable multiple times (e.g. get the total Count of records first and then iterate thru variable in For Each loop or bind it to a control &#8211; you will get an error:
<p><strong style='color:red'><em>The query results cannot be enumerated more than once</em></strong></p>
<p>This happens because underlying stored procedure can be executed only once and result returned by the Linq2Sql method is of type <em>ISingleResult(Of T)</em>. The solution is to convert the result to in-memory list:</p>
<pre class="brush: vb; title: ; notranslate">Dim aResults = MyDbContext.MyProcedure(2011).ToList()</pre>
<p>This way the result becomes of type <em>Generic.List(Of T)</em> and you&#8217;re free to do whatever you need with it as many times as you need.
</li>
</ol>
<div id="crp_related"><h4>Related Posts:</h4><ul><li><a href="http://CodeCorner.galanter.net/2011/08/05/sql-server-stored-procedure-runs-slow-from-net-code/" rel="bookmark" class="crp_title">SQL Server stored procedure runs slow from .NET code</a></li><li><a href="http://CodeCorner.galanter.net/2011/08/19/elusive-string-or-binary-data-would-be-truncated-error/" rel="bookmark" class="crp_title">Elusive &#8220;String or binary data would be truncated&#8221; error</a></li></ul></div>]]></content:encoded>
			<wfw:commentRss>http://CodeCorner.galanter.net/2011/06/14/stored-procedure-in-linq2sql-query/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>SSRS: How to implement build-in parameter based on external parameter passed from ReportViewer</title>
		<link>http://CodeCorner.galanter.net/2011/04/29/ssrs-how-to-implement-build-in-parameter-based-on-external-parameter-passed-from-reportviewer/</link>
		<comments>http://CodeCorner.galanter.net/2011/04/29/ssrs-how-to-implement-build-in-parameter-based-on-external-parameter-passed-from-reportviewer/#comments</comments>
		<pubDate>Fri, 29 Apr 2011 22:05:08 +0000</pubDate>
		<dc:creator>Yuriy</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[reporting]]></category>

		<guid isPermaLink="false">http://CodeCorner.galanter.net/?p=1280</guid>
		<description><![CDATA[Imagine following scenario: an SSRS report has a dropdown list &#8220;lookup&#8221; parameter based on a stored procedure. When report runs, user selects a value from the dropdown, clicks &#8220;View Report&#8221; and report is generated. The challenge is &#8211; the &#8220;lookup&#8221; parameter (and underlying stored procedure) needed to be filtered by another &#8220;filter&#8221; parameter &#8211; and [...]]]></description>
			<content:encoded><![CDATA[<p>Imagine following scenario: an SSRS report has a dropdown list &#8220;lookup&#8221; parameter based on a stored procedure. When report runs, user selects a value from the dropdown, clicks &#8220;View Report&#8221; and report is generated. The challenge is &#8211; the &#8220;lookup&#8221; parameter (and underlying stored procedure) needed to be filtered by another &#8220;filter&#8221; parameter &#8211; and this one is not available in SSRS interface, but instead is passed from ReportViewer control from an ASP.NET application.</p>
<p>In order to successfully implement this use case 2 items need to be addressed:</p>
<p><strong>First</strong> in the report itself parameters need to be ordered in such way so &#8220;filter&#8221; comes before &#8220;dropdown&#8221;. Parameters can easily be arranged in Business Intelligent Development Studio, by expanding Parameters node, selecting a parameter, and using arrow buttons in Report Data menu.</p>
<p><strong>Second</strong> in the ASP.NET application, configuring ReportViewer control (setting credentials, server URL, report path and our &#8220;filter&#8221; parameter) needs to be done in <em>Page_Init</em> event in the &#8220;<em>If Not IsPostback</em>&#8221; block.</p>
<div id="crp_related"><h4>Related Posts:</h4><ul><li><a href="http://CodeCorner.galanter.net/2008/05/07/dynamic-number-of-fields-in-a-query-for-ssrs-2005/" rel="bookmark" class="crp_title">Dynamic number of fields in a query for SSRS 2005</a></li><li><a href="http://CodeCorner.galanter.net/2011/01/04/ssrs-query-execution-failed-expected-parameter/" rel="bookmark" class="crp_title">SSRS Query execution failed &#8230; Expected parameter &#8230;</a></li></ul></div>]]></content:encoded>
			<wfw:commentRss>http://CodeCorner.galanter.net/2011/04/29/ssrs-how-to-implement-build-in-parameter-based-on-external-parameter-passed-from-reportviewer/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Individual Sorting of SELECT queries in the UNION</title>
		<link>http://CodeCorner.galanter.net/2011/03/15/individual-sorting-of-select-queries-in-the-union/</link>
		<comments>http://CodeCorner.galanter.net/2011/03/15/individual-sorting-of-select-queries-in-the-union/#comments</comments>
		<pubDate>Tue, 15 Mar 2011 19:54:13 +0000</pubDate>
		<dc:creator>Yuriy</dc:creator>
				<category><![CDATA[SQL]]></category>
		<category><![CDATA[workaround]]></category>

		<guid isPermaLink="false">http://CodeCorner.galanter.net/?p=1220</guid>
		<description><![CDATA[UNION is a very common operator used in SQL, it allows to combine result of multiple queries into one. Unfortunately if you want to sort this unified resultset sorting is applied to entire result at once. But what if you wan to sort queries-participants individually? Let&#8217;s say you have 2 following queries from Northwind database: [...]]]></description>
			<content:encoded><![CDATA[<p><strong>UNION</strong> is a very common operator used in SQL, it allows to combine result of multiple queries into one. Unfortunately if you want to sort this unified resultset sorting is applied to entire result at once. But what if you wan to sort queries-participants individually?</p>
<p>Let&#8217;s say you have 2 following queries from Northwind database:</p>
<pre class="brush: sql; title: ; notranslate">SELECT TOP (5) CompanyName FROM Suppliers ORDER BY CompanyName</pre>
<pre class="brush: plain; title: ; notranslate">Aux joyeux ecclésiastiques
Bigfoot Breweries
Cooperativa de Quesos 'Las Cabras'
Escargots Nouveaux
Exotic Liquids</pre>
<p>and</p>
<pre class="brush: sql; title: ; notranslate">SELECT TOP (5) ProductName FROM Products ORDER BY ProductName</pre>
<pre class="brush: plain; title: ; notranslate">Alice Mutton
Aniseed Syrup
Boston Crab Meat
Camembert Pierrot
Carnarvon Tigers</pre>
<p>And now you want to combine them into a single result, adding title lines to separate each result. The direct approach would be:</p>
<pre class="brush: sql; title: ; notranslate">SELECT 'Suppliers' AS Name
UNION
SELECT TOP (5) CompanyName FROM Suppliers
UNION
SELECT 'Products'
UNION
SELECT TOP (5) ProductName FROM Products
ORDER BY Name</pre>
<p>But result is far from what we wanted</p>
<pre class="brush: plain; highlight: [11,12]; title: ; notranslate">Alice Mutton
Aniseed Syrup
Aux joyeux ecclésiastiques
Bigfoot Breweries
Boston Crab Meat
Camembert Pierrot
Carnarvon Tigers
Cooperativa de Quesos 'Las Cabras'
Escargots Nouveaux
Exotic Liquids
Products
Suppliers</pre>
<p>Entire resultset is sorted uniformally and products are mixed with suppliers.<br />
<span id="more-1220"></span><br />
The solution is to designate a special &#8220;Sort By&#8221; field in each query. Consider following revision of previous UNION</p>
<pre class="brush: sql; title: ; notranslate">SELECT 'Suppliers' AS Name, 1 as SortBy
UNION
SELECT TOP (5) CompanyName, 2 FROM Suppliers
UNION
SELECT 'Products', 3
UNION
SELECT TOP (5) ProductName, 4 FROM Products
ORDER BY SortBy, Name</pre>
<p>Here were added a numeric field to each query, 1 to the 1st, 2 to the 2nd, 3 to the 3rd and 4 to the 4th. And then in the ORDER BY clause we sort by this field first and the name second. The result is properly sorted list of suppliers &amp; products:</p>
<pre class="brush: plain; highlight: [1,7]; title: ; notranslate">
Suppliers                                   1
Aux joyeux ecclésiastiques                  2
Bigfoot Breweries                           2
Cooperativa de Quesos 'Las Cabras'          2
Escargots Nouveaux                          2
Exotic Liquids                              2
Products                                    3
Alice Mutton                                4
Aniseed Syrup                               4
Boston Crab Meat                            4
Camembert Pierrot                           4
Carnarvon Tigers                            4</pre>
<div id="crp_related"><h4>Related Posts:</h4><ul><li><a href="http://CodeCorner.galanter.net/2011/08/29/tsql-filling-missing-date-range/" rel="bookmark" class="crp_title">TSQL: Filling missing date range</a></li><li><a href="http://CodeCorner.galanter.net/2009/06/25/t-sql-string-aggregate-in-sql-server/" rel="bookmark" class="crp_title">T-SQL String Aggregate in SQL Server</a></li></ul></div>]]></content:encoded>
			<wfw:commentRss>http://CodeCorner.galanter.net/2011/03/15/individual-sorting-of-select-queries-in-the-union/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>TSQL: Remove duplicate records. Clean and Simple</title>
		<link>http://CodeCorner.galanter.net/2011/02/02/tsql-remove-duplicate-records/</link>
		<comments>http://CodeCorner.galanter.net/2011/02/02/tsql-remove-duplicate-records/#comments</comments>
		<pubDate>Wed, 02 Feb 2011 22:20:33 +0000</pubDate>
		<dc:creator>Yuriy</dc:creator>
				<category><![CDATA[SQL]]></category>
		<category><![CDATA[cool]]></category>
		<category><![CDATA[Data]]></category>
		<category><![CDATA[solution]]></category>

		<guid isPermaLink="false">http://CodeCorner.galanter.net/?p=1127</guid>
		<description><![CDATA[It&#8217;s a common scenario, your table has several records with identical values and you need to leave only one, deleting the rest. Here is a generic TSQL query (SQL Server 2005 and above) that does just that in a few lines: Here ORIGINAL_TABLE is your table with duplicates. FIELD1 and FIELD2 are columns with duplicates [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s a common scenario, your table has several records with identical values and you need to leave only one, deleting the rest. Here is a generic TSQL query (SQL Server 2005 and above) that does just that in a few lines:</p>
<pre class="brush: sql; title: ; notranslate">WITH DUP_TABLE AS
   (SELECT ROW_NUMBER()
    OVER (PARTITION BY FIELD1, FIELD2 ORDER BY FIELD1, FIELD2) As ROW_NO
    FROM ORIGINAL_TABLE)
DELETE FROM DUP_TABLE WHERE ROW_NO &gt; 1
</pre>
<p>Here <strong>ORIGINAL_TABLE</strong> is your table with duplicates. <strong>FIELD1</strong> and <strong>FIELD2</strong> are columns with duplicates value (feel free to add or remove columns to suit your needs). Internal query assigns a row number to each duplicate record and DELETE statements that uses that CTE deletes all the rows except the one with Row Number = 1</p>
<div id="crp_related"><h4>Related Posts:</h4><ul><li><a href="http://CodeCorner.galanter.net/2012/01/19/rownumber-is-affected-by-if-statement/" rel="bookmark" class="crp_title">@@ROWCOUNT is affected by IF statement</a></li><li><a href="http://CodeCorner.galanter.net/2009/12/11/wordpress-mu-delete-empty-posts/" rel="bookmark" class="crp_title">WordPress MU: Delete Empty Posts</a></li></ul></div>]]></content:encoded>
			<wfw:commentRss>http://CodeCorner.galanter.net/2011/02/02/tsql-remove-duplicate-records/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>SSRS Query execution failed &#8230; Expected parameter &#8230;</title>
		<link>http://CodeCorner.galanter.net/2011/01/04/ssrs-query-execution-failed-expected-parameter/</link>
		<comments>http://CodeCorner.galanter.net/2011/01/04/ssrs-query-execution-failed-expected-parameter/#comments</comments>
		<pubDate>Tue, 04 Jan 2011 22:34:14 +0000</pubDate>
		<dc:creator>Yuriy</dc:creator>
				<category><![CDATA[SQL]]></category>
		<category><![CDATA[bug]]></category>
		<category><![CDATA[Data]]></category>
		<category><![CDATA[Quick fix]]></category>

		<guid isPermaLink="false">http://CodeCorner.galanter.net/?p=1121</guid>
		<description><![CDATA[Consider following scenario: While developing for SQL Server Reporting Services you created a report in Business Intelligent Studio (or generated RDL file elsewhere and then added it to Studio&#8217;s project). Everything works fine, you&#8217;re able to preview report. And then you need to change Data Source (one example: you created a shared Data Source and [...]]]></description>
			<content:encoded><![CDATA[<p>Consider following scenario: While developing for SQL Server Reporting Services you created a report in Business Intelligent Studio (or generated RDL file elsewhere and then added it to Studio&#8217;s project). Everything works fine, you&#8217;re able to preview report. And then you need to change Data Source (one example: you created a shared Data Source and now want your report to use it). After you do that any attempt to run the report results in error: <em>Query execution failed &#8230; Expected parameter &#8230;</em>.</p>
<p>The reason in this case &#8211; when you change the data source thru GUI &#8211; it resets query used by the report. It can change query type from StoredProcedure to Text and also remove all default query parameters (hence error above).</p>
<p>There&#8217;re 2 possible solutions here: First &#8211; instead of using GUI, manually change Data Source in the XML source of the report file (in Solution Explorer right mouse click on the report file and select &#8220;View Code&#8221;). You will have to change it in several places, so be careful. Second &#8211; re-create query with its default parameters after changing Data Source in GUI.</p>
<div id="crp_related"><h4>Related Posts:</h4><ul><li><a href="http://CodeCorner.galanter.net/2011/04/29/ssrs-how-to-implement-build-in-parameter-based-on-external-parameter-passed-from-reportviewer/" rel="bookmark" class="crp_title">SSRS: How to implement build-in parameter based on external parameter passed from ReportViewer</a></li><li><a href="http://CodeCorner.galanter.net/2008/05/07/dynamic-number-of-fields-in-a-query-for-ssrs-2005/" rel="bookmark" class="crp_title">Dynamic number of fields in a query for SSRS 2005</a></li></ul></div>]]></content:encoded>
			<wfw:commentRss>http://CodeCorner.galanter.net/2011/01/04/ssrs-query-execution-failed-expected-parameter/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

