Wednesday, March 28, 2012
Parameter is null, return all?
procedure on the table. Now lets say a row contains the numbers 1
through 5, and i had a parameter in the sp that would be given one of
those values, and then return the corresponding row, but if they it
were passed a null value, how could i make it return all objects?Right
now i have this but i also want to return level 2, 3, 4, 5, etc:
SecurityID = ISNULL(@.SecurityLevel, '1')You can use a WHERE clause like
WHERE (
@.SecurityLevel = SecurityID
OR
@.SecurityLevel IS NULL
)
This will often perform poorly, because there is no one
query plan that can efficiently serve both cases, and another
thing to try is
WHERE (
SecurityID >= COALESCE(@.SecurityLevel,-2147483648)
AND
SecurityID <= COALESCE(@.SecurityLevel,2147483647)
)
(or with other values if the type of SecurityID is not INT).
Steve Kass
Drew University
nbs.tag@.gmail.com wrote:
>Hi, heres the problem, ive got a table, and im calling a stored
>procedure on the table. Now lets say a row contains the numbers 1
>through 5, and i had a parameter in the sp that would be given one of
>those values, and then return the corresponding row, but if they it
>were passed a null value, how could i make it return all objects?Right
>now i have this but i also want to return level 2, 3, 4, 5, etc:
>SecurityID = ISNULL(@.SecurityLevel, '1')
>
>|||SecurityID = @.SecurityLevel OR @.SecurityLevel IS NULL
Also see
http://sommarskog.se/dyn-search.html
--
Regards
Roji. P. Thomas
http://toponewithties.blogspot.com
<nbs.tag@.gmail.com> wrote in message
news:1148911602.878618.143780@.j55g2000cwa.googlegroups.com...
> Hi, heres the problem, ive got a table, and im calling a stored
> procedure on the table. Now lets say a row contains the numbers 1
> through 5, and i had a parameter in the sp that would be given one of
> those values, and then return the corresponding row, but if they it
> were passed a null value, how could i make it return all objects?Right
> now i have this but i also want to return level 2, 3, 4, 5, etc:
> SecurityID = ISNULL(@.SecurityLevel, '1')
>
Friday, March 23, 2012
ParallelPeriod: Same Day Last Month in long months
I am using the following MDX query to return same day last month values:
WITH
MEMBER [Measures].[Same Day Last Month] AS
'(ParallelPeriod([Reporting Date].[Year - Quarter - Month - Date].[Month],1),[Measures].[Active Account Indicator])'
SELECT
{[Measures].[Active Account Indicator],[Measures].[Same Day Last Month]} ON COLUMNS,
NON EMPTY {[Reporting Date].[Date].Members} ON ROWS
FROM [Financial]
This works for most days. However, for the last day of the month this cannot work when the current month has more days than the previous month. For example, on March 29, 30 and 31, the query will return NULL for [Same Day Last Month], since February 29, 30, 31 is an invalid date.
I am sure others have run into the same problem. What is the best way to solve this?
I'm grateful for any insights.
Dan
This could perhaps be more efficiently handled in scoped MDX script; but a recursive approach like this should work (except in the first month):
WITH
MEMBER [Measures].[Same Day Last Month] AS
iif(ParallelPeriod([Reporting Date].[Year - Quarter - Month - Date].[Month]) is null,
([Reporting Date].[Year - Quarter - Month - Date].PrevMember,
[Measures].[Same Day Last Month]),
(ParallelPeriod([Reporting Date].[Year - Quarter - Month - Date].[Month]),
[Measures].[Active Account Indicator]))
|||Thank you, Deepak. I appreciate your response.
I believe I would have to use nested recursive statements for March 31. One month ago would indicate February 31, previous day would be February 30, and so forth until a valid date is reached.
However, this lead me to another solution which worked and follows our business rules: The last day of any month always contains values. Therefore, I was able to solve my problem using the following approach, employing the IsLeaf(), and the ClosingPeriod() function:
WITH
MEMBER [Measures].[Same Day Last Month] AS
'IIf(
--valtest
IsLeaf(
ParallelPeriod(
[Reporting Date].[Year - Quarter - Month - Date].[Month],
1
)
,
--valtrue
(
ParallelPeriod(
[Reporting Date].[Year - Quarter - Month - Date].[Month],
1
),
[Measures].[Active Account Indicator]
)
,
--valfalse
(
ClosingPeriod(
[Reporting Date].[Year - Quarter - Month - Date].[Date],
ParallelPeriod(
[Reporting Date].[Year - Quarter - Month - Date].[Month],
1
[Reporting Date].[Year - Quarter - Month - Date].CurrentMember.Parent
)
),
[Measures].[Active Account Indicator]
)
) --End IIf
'
SELECT
{[Measures].[Active Account Indicator],[Measures].[Same Day Last Month]} ON COLUMNS,
NON EMPTY {[Reporting Date].[Date].Members} ON ROWS
FROM [Financial]
ParallelPeriod that never returns null
I'm sure this is easy, but I haven't been able to cook up the secret sauce: I need a function like ParallelPeriod that will always return a member (unless I'm asking for a member that predates the oldest member in the dimension, when null is perfectly fine).
For example, ParallelPeriod([Month],1,[2006].[December].[31]) returns null. Instead, I want to get back [2006].[November].[30] (the last day of the month).
What's the secret?
There are many ways to do it. One way is to have an attribute which keeps number of days needed to go back to get to the day in the previous month. Then you will use
Date.CurrentMember.Lag(Date.DaysToGoBack.MemberValue)
for December 30 it will be 30, and for December 31 it will be 31 - so both of them will land on November 30.
|||How 'bout a way that doesn't involve changing the definition of the cube?|||Possible too, but it won't have as good performance as the solution I proposed first. Again, there are many ways, but they revolve around the following theme (note that the formula below is only valid for the Month level. I am not sure what you want to do on the other levels).
IIF(Date.CurrentMember IS Date.CurrentMember.Parent.LastChild, Date.CurrentMember.Parent.PrevMember.LastChild, ParallelPeriod(...))
|||OK, I see the pattern. The solution you propose above won't quite work (think of March), but it's close enough to something that will work to see where to take it.
If I decide that I really need this function, I'll probably go with the first suggestion you made, since I can still change the cube design at this point, I was just looking for a wider variety of options.
Thanks for the suggestions!
Monday, March 12, 2012
Paging query
I have created a stored proc for paging on a datalist which uses a objectDataSource.
I have a output param itemCount which should return the total rows. Them I am creating a temp table to fetch the records for each page request. My output param works fine if I comment out all the other select statements. But returns null with them. Any help would be appreciated.
CREATE PROCEDURE [dbo].[CMRC_PRODUCTS_GetListByCategory]
(
@.categoryID int,
@.pageIndex INT,
@.numRows INT,
@.itemCount INT OUTPUT
)
AS
SELECT @.itemCount= COUNT(*) FROM CMRC_Products whereCMRC_Products.CategoryID=@.categoryID
Declare @.startRowIndex INT;
Declare @.finishRowIndex INT;
set @.startRowIndex = ((@.pageIndex -1) * @.numRows) + 1;
set @.finishRowIndex = @.pageIndex * @.numRows
DECLARE @.tCat TABLE (TID int identity(1,1),ProductID int, CategoryID int, SellerUserName varchar(100), ModelName varchar(100), Medium varchar(50),
ProductImage varchar(100),UnitCost money,Description varchar(1500), CategoryName varchar(100), isActive bit,weight money)
INSERT INTO @.tCat(ProductID, CategoryID,SellerUserName,ModelName,Medium,ProductImage,UnitCost,Description,CategoryName, isActive,weight)
SELECT CMRC_Products.ProductID, CMRC_Products.CategoryID, CMRC_Products.SellerUserName, CMRC_Products.ModelName, CMRC_Products.Medium,CMRC_Products.ProductImage,
CMRC_Products.UnitCost, CMRC_Products.Description, CMRC_Categories.CategoryName, CMRC_Products.isActive,CMRC_Products.weight
FROM CMRC_Products INNER JOIN
CMRC_Categories ON CMRC_Products.CategoryID = CMRC_Categories.CategoryID
WHERE (CMRC_Products.CategoryID = @.categoryID) AND (CMRC_Products.isActive = 1)
SELECT ProductID, CategoryID,SellerUserName,ModelName,Medium,ProductImage,UnitCost,Description,CategoryName, isActive,weight
FROM @.tCat
WHERE TID >= @.startRowIndex AND TID <= @.finishRowIndex
GO
spawned:
My output param works fine if I comment out all the other select statements. But returns null with them.
Strange! Other select statements should not effect the output param as non of them refereneces the output param. How did you get the output param's value after executing the sp? Will the output param work fine if you directly execute the stored procedure in SQL via Query Analyzer (or Management Studio) without commenting out some statements?
|||You are correct, I tested in Query Analyser and the Output was returned OK.
The issue was that the method was returning a DataReader along with a output param. The two don't get along! You have to close the DataReader before the output param is visible. This is 'by design' accourding to MS.http://support.microsoft.com/?id=308051 (See resolution section). Moving to the end of the recordset didn't seem to work but close it does.
This was a real pain as I had to change the method to Read the data into a list<Product> then close the Reader, then set reference to my output param.
Anyway all done now and works a treat. Thanks for you advice.
|||Then how about returning the count as a result set instead of putting it in the output parameter? I mean you can write your stored procedure this way:
CREATE PROCEDURE [dbo].[CMRC_PRODUCTS_GetListByCategory]
(
@.categoryID int,
@.pageIndex INT,
@.numRows INT,
)
AS
SELECT COUNT(*) FROM CMRC_Products whereCMRC_Products.CategoryID=@.categoryID
//do other things
go
And then in the code you can get the count from the first result set using SqlDataReader.
Ok, I thought only DataSets alowed that (ie Tables[0], Table[1] etc, or does the Reader just return it at the end of the recordset.
I'll have a play around with it. Thanks for the tip.
Cheers,Shaun.
|||
I am having exa ctly the same problem.
You mentioned that you used a method to Read the data into a list<Product> then close the Reader, then set reference to my output param. This is exactly what i am trying to do now could you tell me the code for this.
many thanks
martin
|||In my Product.cs I have the following new method:
//Used for paged results in catagory searchpublicvoid ProductList(int ProductID,string Medium,string ModelName,string ProductImage,double UnitCost,bool IsAdult){
_ProductID = ProductID;
_Medium = Medium;
_ModelName = ModelName;
_ProductImage = ProductImage;
_UnitCost = UnitCost;
_IsAdult = IsAdult;
}
***************************
In my CatalogManager .cs (I didn't put it in the provider project as it is a pain in the ar*e to maintain) I have the following:
public
staticList <Product> GetProductsByCategoryPaging(int categoryID,int pageIndex,int numRows,outint itemCount){
using (SqlConnection connection =newSqlConnection(ConfigurationManager.ConnectionStrings["CommerceTemplate"].ConnectionString)){
using (SqlCommand command =newSqlCommand("CMRC_PRODUCTS_GetListByCategoryPaging", connection)){
command.CommandType =
CommandType.StoredProcedure;command.Parameters.Add(
"@.itemCount",SqlDbType.Int, 4);command.Parameters[
"@.itemCount"].Direction =ParameterDirection.Output;command.Parameters.Add(
newSqlParameter("@.categoryID", categoryID));command.Parameters.Add(
newSqlParameter("@.pageIndex", pageIndex));command.Parameters.Add(
newSqlParameter("@.numRows", numRows));connection.Open();
//populate listList<Product> list =newList<Product>();using (SqlDataReader rdr = command.ExecuteReader()) {while (rdr.Read()) {Product temp =newProduct();temp.ProductList(
(
int)rdr["ProductID"],rdr[
"Medium"].ToString(),rdr[
"ModelName"].ToString(),rdr[
"ProductImage"].ToString(),Convert.ToDouble (rdr["UnitCost"]),(
bool)rdr["IsAdult"]);list.Add(temp);
}
rdr.Close();
}
itemCount = (
int)command.Parameters["@.itemCount"].Value;return list;}
}
}
You'll need to include the this declaration in the CatalogManager:
using System.Collections.Generic;
Good luck I feel you pain :-)
|||
really, many thanks for that it was driving me crazy
cheers
martin
|||Once again many thanks for your help with this. Everhting is working fine.
Just one question did you use querystrings and if you did, how did you validate
them. I am having a lot of problems trying to figure out how to do this.
many thanks for all your help
martin
|||
Yes I did use query strings. My catalog page handles many queries.
I had a switch statement in the Page Load.
switch (SearchType) <== I have a param for query type.{
case"c"://category searchcid =
Convert.ToInt32(Request.QueryString["cid"]);dlCatalog.DataSource = objDSCategory;
dlCatalog.DataBind();
break;case"a"://artist searchdlCatalog.DataSource = objDSArtist;
dlCatalog.DataBind();
break;etc
}
in the obj DataSource in aspx:
<
asp:ObjectDataSourceID="objDSGallery"runat="server"OldValuesParameterFormatString="{0}"SelectMethod="GetProductsByGalleryPaging"TypeName="CatalogManager"OnSelected="objDSGallery_Selected"OnSelecting="objDSGallery_Selecting"><SelectParameters><asp:QueryStringParameterName="GalleryID"QueryStringField="gid"Type="Int32"/><asp:QueryStringParameterName="pageIndex"QueryStringField="PageIndex"DefaultValue="0"/><asp:QueryStringParameterName="numRows"QueryStringField="NumRows"DefaultValue="6"/><asp:ParameterName="itemCount"Direction="Output"Type="Int32"/></SelectParameters></asp:ObjectDataSource>Let me know if you have any more dramas, I can email you the code I'm using for reference.
The OnSelected and Selecting methods are used for updating the paging links.
I can email you the code if you like.
Cheers,Shaun.
|||thanks for your reply
i would be grateful for the code my address istbcmartingharvey@.yahoo.co.jp
many thanks
martin
|||
Is your Yahoo account still active? got a return reply saying:
554 delivery error: dd This user doesn't have a yahoo.co.jp account (tbcmartingharvey@.yahoo.co.jp)
Is that your correct mail address?
Cheers,Shaun
ps I'll be away for several days (biz not pleasure :-( ) so will not get the code to you till Tues. Probably best I provide it as a download from my server so other users can access it too.
|||thanks for your reply shaun
must be the summer heat
itstbcmartinharvey@.yahoo.co.jp
thank you
martin
Friday, March 9, 2012
Paging in MDX
Hi
I am new to mdx.i want to know can we implement paging in mdx query? is there any function in mdx so that i can return resultset based on count.i am using topcount function to return 10 rows.but i want to return result for next top 10 and so on.. in same query. like we do in paging.
Thanks in advance
There are probably ways of doing this, one that comes to mind would be to use a combination of topcount and tail
eg. page1... TopCount( <set>, <expression>, 10)
page2... TopCount( <set>, <expression>, 20).tail(10)