Showing posts with label returns. Show all posts
Showing posts with label returns. Show all posts

Thursday, March 29, 2012

'Default' NON_EMPTY_BEHAVIOR behavior...

Hi,

The below query returns 20 rows when run against our production DW. When the NON_EMPTY_BEHAVIOR is removed, it returns 10 rows. Note the lack of a member list on the N_E_B. Anyone else seen this, or have any ideas as to why it's causing me a 'problem'?

WITH MEMBER

[Container].[Container Type].[AllCalc] AS [Container].[Container Type].[All],

NON_EMPTY_BEHAVIOR={}

SELECT

([Measures].[Container Load Count]) ON COLUMNS,

NON EMPTY

[Trade].[Trade].&[EAST_AFRICA] * [Container].[Container Number].[All].Children ON ROWS

FROM [DW_SM]

WHERE (

<various slicers>,

[Container].[Container Type].[AllCalc]

)

Thanks,

Will.

You should remove NON_EMPTY_BEHAVIOR from your calculated member, because it is set incorrectly. Specifying an empty set for NEB is FAAP always wrong. And really to get any benefit out of it in the form you are trying to use it, it should've only been used on calculated measure, not on calculated member.

DEFAULT keyword performance

I have a function which performs a query and returns a table. The one
parameter that can get passed in is a date which defaults to NULL.
There is an IF statement in the function that will set the paramter to
an actual date if null. If I call the function while passing in a date
the function comes back a second or 2 later. But if I pass in DEFAULT
to the function, the same query takes 8 minutes. See code below and
sample call below.

CREATE FUNCTION fCalculateProfitLossFromClearing (
@.TradeDate DATETIME = NULL
)
RETURNS @.t TABLE (
[TradeDate] DATETIME,
[Symbol] VARCHAR(15),
[Identity] VARCHAR(15),
[Exchange] VARCHAR(5),
[Account] VARCHAR(10),
[Value] DECIMAL(18, 6)
)
AS
BEGIN
-- Use previous trading date if none specified
IF @.TradeDate IS NULL
SET @.TradeDate = Supporting.dbo.GetPreviousTradeDate()

-- Make the query
INSERT @.t
SELECT
@.TradeDate,
tblTrade.[Symbol],
tblTrade.[Identity],
tblTrade.[Exchange],
tblTrade.[Account],
SUM((CASE tblTrade.[Side] WHEN 'B' THEN -ABS(tblTrade.[Quantity])
ELSE ABS(tblTrade.[Quantity]) END) * (tblPos.[ClosingPrice] -
tblTrade.[Price])) AS [Value]
FROM
Historical.dbo.ClearingTrade tblTrade
LEFT JOIN Historical.dbo.ClearingPosition tblPos ON (@.TradeDate =
tblPos.[TradeDate] AND tblTrade.[Symbol] = tblPos.[Symbol] AND
tblTrade.[Identity] = tblPos.[Identity])
WHERE
([TradeTimestamp] >= @.TradeDate AND [TradeTimestamp] < DATEADD(DAY,
1, @.TradeDate))
GROUP BY tblTrade.[Symbol],tblTrade.[Identity],tblTrade.[Exchange],tblTrade.[Account]

RETURN
END

If I call the function as

SELECT * FROM fCalculateProfitLossFromClearing('09/25/2003')

it returns in 2 seconds.

If I call the function as

SELECT * FROM fCalculateProfitLossFromClearing(DEFAULT)

in which GetPreviousTradeDate() will set @.TradeDate to 09/25/2003 it
returns in 8 minutes.[posted and mailed, please reply in news]

Jason (JayCallas@.hotmail.com) writes:
> I have a function which performs a query and returns a table. The one
> parameter that can get passed in is a date which defaults to NULL.
> There is an IF statement in the function that will set the paramter to
> an actual date if null. If I call the function while passing in a date
> the function comes back a second or 2 later. But if I pass in DEFAULT
> to the function, the same query takes 8 minutes. See code below and
> sample call below.

The query seems familiar. :-)

The reason for this is that when SQL Server builds the query plan,
it considers the value of the input parameter. When you provide an
explicit date, SQL Server can consult the statistics for the table
and see that the value you provided is very selective, and use the
index.

But if you provide NULL, SQL Server will build the query plan on that
assumption. Obviously a NULL value would return no rows, but SQL Server
never makes any assumptions that could yield incorrect results. Since
you WHERE condition is for a range, SQL Server appears to prefer to
scan the table, than using a non-clustered index.

--
Erland Sommarskog, SQL Server MVP, sommar@.algonet.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||>
> The query seems familiar. :-)
> The reason for this is that when SQL Server builds the query plan,
> it considers the value of the input parameter. When you provide an
> explicit date, SQL Server can consult the statistics for the table
> and see that the value you provided is very selective, and use the
> index.
> But if you provide NULL, SQL Server will build the query plan on that
> assumption. Obviously a NULL value would return no rows, but SQL Server
> never makes any assumptions that could yield incorrect results. Since
> you WHERE condition is for a range, SQL Server appears to prefer to
> scan the table, than using a non-clustered index.

I hate the restart this thread but I have hit a brick wall...

I am at a lose of whether to creat functions or stored procedures (or
even views).

The below questions/issues are based on a need to return information
on a particular date for one to many symbols.

For my example lets say 15 symbols. You could do a query like Symbol =
'a' OR Symbol = 'b' OR Symbol... but it would make more sense to do
Symbol IN ('a','b',...))

I would also like to give my functions and stored procedures to use a
default date if none is specified. I created a function named
GetPreviousTradeDate() which does this based on a calendar.

SO here is how I see it.

Stored procedures seem to be the fastest in terms of returning data
back. But they seem to be limited in the sense that they can return
ONE row or ALL the rows since you cannot pass in a variable list of
symbols. You also cannot use the SP as part of a query. You could just
return all the rows back to the client and do filter or searching on
that end but that does not seem efficient or professional.

A function also does not let you pass in a variable list of symbols
but at least you can use it in a query. You could do something like
SELECT * FROM TheFunction() WHERE Symbol IN ('a','b',...). All this
happens at the server side and only the needed rows gets sent back.

But functions seem to have MAJOR performance problems when default
values are passed in. When I pass in a specific date the query takes a
few seconds but when I pass in DEFAULT and set the date to the results
of the GetPreviousTradeDate() function the query takes anywhere from 8
minutes to 15 minutes. (This even happens if I do not use the
GetPreviousTradeDate() function and set my parameter to a hard-coded
value)

Any thoughts or comments would be appreciated.|||Jason (JayCallas@.hotmail.com) writes:
> A function also does not let you pass in a variable list of symbols
> but at least you can use it in a query. You could do something like
> SELECT * FROM TheFunction() WHERE Symbol IN ('a','b',...). All this
> happens at the server side and only the needed rows gets sent back.

I happen to have an article on my web site that discusses this case
in detail. You don't have to read all of it, but you can just get
the function you need at
http://www.algonet.se/~sommar/array...html#iterative.

> But functions seem to have MAJOR performance problems when default
> values are passed in. When I pass in a specific date the query takes a
> few seconds but when I pass in DEFAULT and set the date to the results
> of the GetPreviousTradeDate() function the query takes anywhere from 8
> minutes to 15 minutes. (This even happens if I do not use the
> GetPreviousTradeDate() function and set my parameter to a hard-coded
> value)

The difference is not always that big, but apparently your query is
sensitive for this. I suggest that you split up the procedure in two:

EXEC outer_sp @.date = NULL datetime
IF @.date IS NULL
SELECT @.date = dbo.yourfunctionfordefault()
EXEC inner_sp @.date

And then inner_sp includes the actual query.

For a long treatise on this subject, search on Google news for articles
by Bart Duncan (a escalation engineer at Microsoft) and the phrase
"parameter sniffing".

--
Erland Sommarskog, SQL Server MVP, sommar@.algonet.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||JayCallas@.hotmail.com (Jason) wrote in message news:<f01a7c89.0310141510.28e9c846@.posting.google.com>...
> I hate the restart this thread but I have hit a brick wall...
> I am at a lose of whether to creat functions or stored procedures (or
> even views).
> The below questions/issues are based on a need to return information
> on a particular date for one to many symbols.
> For my example lets say 15 symbols. You could do a query like Symbol =
> 'a' OR Symbol = 'b' OR Symbol... but it would make more sense to do
> Symbol IN ('a','b',...))
> I would also like to give my functions and stored procedures to use a
> default date if none is specified. I created a function named
> GetPreviousTradeDate() which does this based on a calendar.
> SO here is how I see it.
> Stored procedures seem to be the fastest in terms of returning data
> back. But they seem to be limited in the sense that they can return
> ONE row or ALL the rows since you cannot pass in a variable list of
> symbols. You also cannot use the SP as part of a query. You could just
> return all the rows back to the client and do filter or searching on
> that end but that does not seem efficient or professional.
> A function also does not let you pass in a variable list of symbols
> but at least you can use it in a query. You could do something like
> SELECT * FROM TheFunction() WHERE Symbol IN ('a','b',...). All this
> happens at the server side and only the needed rows gets sent back.
> But functions seem to have MAJOR performance problems when default
> values are passed in. When I pass in a specific date the query takes a
> few seconds but when I pass in DEFAULT and set the date to the results
> of the GetPreviousTradeDate() function the query takes anywhere from 8
> minutes to 15 minutes. (This even happens if I do not use the
> GetPreviousTradeDate() function and set my parameter to a hard-coded
> value)
> Any thoughts or comments would be appreciated.

Since the stored procedure has both the speed and the ability to use
default values without performance hit, would it be normal practice or
efficient to send separate queries for each symbol to the stored
procedure? This could result in anywhere from a few to several hundred
calls at a time.|||Jason (JayCallas@.hotmail.com) writes:
> Since the stored procedure has both the speed and the ability to use
> default values without performance hit, would it be normal practice or
> efficient to send separate queries for each symbol to the stored
> procedure? This could result in anywhere from a few to several hundred
> calls at a time.

That does not seem like a good idea. Certainly more efficient to get
data for all symbols at once. See my previous post for suggestions.

--
Erland Sommarskog, SQL Server MVP, sommar@.algonet.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||>> A function also does not let you pass in a variable list of symbols
but at least you can use it in a query ... Any thoughts or comments
would be appreciated. <<

Ever try putting the list of symbols into a one column table and using
an "IN (SELECT parm FROM Parmlist)" instead?

Wednesday, March 21, 2012

Decrypting returns a NULL value

I find it weird when decrypting a column from a baked up database and restoring it to another database. Here's the scenario:

Server1 has Database1.
Database1 has Table1 with two columns encyrpted -- Card Number and SS Number
Encryption and decryption in this Database1 is perfectly fine. Records are encrypted and can be decrypted too.
Now, I tried to backup this Database1 and restore it to another server with SQL 2005 instance called Server2. Of course the columns Card and SS Numbers were encrypted. I tried decrypting the columns using the same command to decrypt in Database1, however, it returns a NULL value Sad

Here's exactly what I did to create the encyprtion and decryption keys on the restored database:
-- Create the master key encryption
CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'myMasterPassword'

-- Create a symetric key
CREATE SYMMETRIC KEY myKey WITH ALGORITHM = DES
ENCRYPTION BY Password='myPassword';
Go

-- Create Card Certificate
CREATE CERTIFICATE myCert WITH SUBJECT = 'My Certificate on this Server';
GO

-- Change symmetric key
OPEN SYMMETRIC KEY myKey DECRYPTION BY PASSWORD = 'myPassword';

-- I then verified if the key is opened
SELECT * FROM sys.openkeys

If I create a new database, say Database2 from that Server2, create table, master key, certificate, and symmetric key. Encrpytion and decryption on Database2 will work!


Any suggestions gurus? I tried all searches and help for almost 2 weeks regarding this issue but nobody could resolve this.

Thanks in advance!

faiga16

3 Posts

I wish I could be more helpful, but all I have to offer is that I think it has to do with your Server master key being different. I was just at a conference where this exact scenario was mentioned and there is a way to use the password (or whatever it is called) to re-encrypt the restored database with the master key so that you can decrypt it.

[ed] sorry it looks like I missed the end of your post. It looks like you're already headed down the path I suggested.

|||

If the two servers are the same OS then I think all you will need to do is run:

ALTER MASTER KEY ADD ENCRYPTION BY SERVICE MASTER KEY

to the new server.

hth,

-Steven Gott

S/DET

SQL Server

|||

Hi Steve,

Yes they have the same OS and SQL version. But executing

ALTER MASTER KEY ADD ENCRYPTION BY SERVICE MASTER KEY

doesnt work too... Sad it prompt an error saying "Create a master key in the database or open the master key in the session before performing this operation"

Is my procedure correct base on what you suggest?

1) restored the Database1

2) run ALTER MASTER KEY ADD ENCRYPTION BY SERVICE MASTER KEY

Sad

|||

I am getting to know my problem.

Before the alter master key command I opened the master key by open master key decryption by password command. Now it prompts an error that the decryption password I supplied was incorrect. Is there a way that I could know the master key encryption/decryption password? I just got here with all the encryption/decryption set up. Nobody remember the master key password Sad duh!


|||

They are quite sure the master key they gave me was the one they used before.

"The key is not decrypted using the specified decryptor"

|||

From the error you are getting back, it seems like the password to decrypt the master key (DBMK) is not correct. The passwords are case sensitive; make sure it is typed exactly as it was originally created.

If you have a backup of the DBMK, you can try restoring the backup on top of the current copy (it should be the same DBMK) using the RESTORE MASTER KEY … FORCE statement.

NOTE: As you are using the force option, make sure you have a copy of the original DB in case the DBMK from the backup doesn’t match the one in your DB.

If the original server still exists, there may be one possibility: you can try to restore the DB on the original server and see if you can still access the DBMK based on the original service master key encryption. From there you can try to regenerate the DBMK (ALTER MASTER KEY REGENERATE) to establish a new DBMK password. I am not sure if this one will work, but it may be worth trying it.

I hope this helps.

-Raul Garcia

SDE/T

SQL Server Engine

|||

Thanks! Will test if this would work...

Sunday, March 11, 2012

declare syntax in a UDF

Hi, I'm trying to create a function that returns a table, however I want
to use a local variable in there and enterprise manager ain't liking it!

The error I get is number 156 'incorrect syntax near the keyword
'declare'.. hopefully this is just a simple thing where I've put it in
the wrong place.

The code follows:

CREATE FUNCTION AFGroupedTotals (@.campaign nvarchar(30),@.datefrom
smalldatetime, @.dateto smalldatetime, @.prospect nvarchar(30), @.type
nvarchar(20))

RETURNS TABLE AS
RETURN

declare @.set nvarchar(150)

select "Total Pledged" as info, sum(total) as tot
FROM AFresponseTotals (@.campaign, @.datefrom, @.dateto,@.prospect)

Cheers for any help,
Chris"Not Me" <Noone.is.home@.here.com> wrote in message
news:ckoccr$olo$1@.ucsnew1.ncl.ac.uk...
> Hi, I'm trying to create a function that returns a table, however I want
> to use a local variable in there and enterprise manager ain't liking it!
> The error I get is number 156 'incorrect syntax near the keyword
> 'declare'.. hopefully this is just a simple thing where I've put it in the
> wrong place.
> The code follows:
> CREATE FUNCTION AFGroupedTotals (@.campaign nvarchar(30),@.datefrom
> smalldatetime, @.dateto smalldatetime, @.prospect nvarchar(30), @.type
> nvarchar(20))
> RETURNS TABLE AS
> RETURN
> declare @.set nvarchar(150)
> select "Total Pledged" as info, sum(total) as tot
> FROM AFresponseTotals (@.campaign, @.datefrom, @.dateto,@.prospect)
>
> Cheers for any help,
> Chris

You seem to be mixing inline and multi-statement syntax. If you just say
RETURN TABLE, then the rest of the function can only be a single SELECT
statement; if you want to use multiple statements in the function, then you
must define the structure of the table you're returning. See the examples in
Books Online under CREATE FUNCTION.

In your function, you haven't defined the structure of the returned table,
so the only thing you can have in the body of the function is a single
SELECT.

Simon|||Simon Hayes wrote:
> "Not Me" <Noone.is.home@.here.com> wrote in message
> news:ckoccr$olo$1@.ucsnew1.ncl.ac.uk...
>>The error I get is number 156 'incorrect syntax near the keyword
>>'declare'.. hopefully this is just a simple thing where I've put it in the
>>wrong place.
>>
>>The code follows:
>>
>>CREATE FUNCTION AFGroupedTotals (@.campaign nvarchar(30),@.datefrom
>>smalldatetime, @.dateto smalldatetime, @.prospect nvarchar(30), @.type
>>nvarchar(20))
>>RETURNS TABLE AS
>>RETURN
>>declare @.set nvarchar(150)
>>select "Total Pledged" as info, sum(total) as tot
>>FROM AFresponseTotals (@.campaign, @.datefrom, @.dateto,@.prospect)
> You seem to be mixing inline and multi-statement syntax. If you just say
> RETURN TABLE, then the rest of the function can only be a single SELECT
> statement; if you want to use multiple statements in the function, then you
> must define the structure of the table you're returning. See the examples in
> Books Online under CREATE FUNCTION.

Aha! sounds about right, just needed a little shunt in the right
direction.. gonna have nightmares about BOL :p

cheers,
Chris

Wednesday, March 7, 2012

Decimal places for integer divisions

SELECT 1/2 returns 0 in transact sql instead of 0.500000
How do I get it to return 0.5000 ?You need to force SQL Server to not do integer division. Try:

SELECT CAST(1 AS float) / CAST(2 AS float)|||You really have to understand datatypes. I still regularly get questions that resemble this one from developers who've been using SQL for years.

In integer division, one divided by two equals zero with a remainder of one. When you divide one integer by another, integer math is used. If you cast either the dividend or the divisor to a real, then real math will be used (with implicit promotion if needed).

-PatP|||Originally posted by calicocat
You need to force SQL Server to not do integer division. Try:

SELECT CAST(1 AS float) / CAST(2 AS float)

Nah...it'll infer type if you let it...

SELECT 1/2.0|||A little more on my problem.

I have two columns in a table each storing integer values. I would like the division to return a decimal number

eg. select col1/col2 should return a decimal result... Neither of the above solutions work.|||OK, so now you need to convert

USE Northwind
GO

CREATE TABLE myTable99(Col1 int, Col2 int)
GO

INSERT INTO myTable99(Col1,Col2)
SELECT 1,2
GO

SELECT Col1/CONVERT(decimal(8,4),Col2)
FROM myTable99
GO

DROP TABLE myTable99
GO

Decimal or Float Type in Percent

Below is a sniplet of a select expression that returns a decimal number like
.6153329998
The result is correct, but when I say FormatPercent(objRS("myPercent"),3) in
ASP, I get a type mismatch error.
Both myField1 and myField2 are integer type. I have to CONVERT myField1 into
decimal in order to get a correct return in QA.
Can someone suggest a better data type to convert myField1 so not only will
myPercent render correct in QA, but also allow me to use FormatPercent in
ASP?
CODE:
SUM(CONVERT(DECIMAL(18, 10), myField1)) / SUM(myField2) AS myPercentHi
You may want to use your convert function after summing
CONVERT(DECIMAL(18, 10), SUM(myField1))/ SUM(myField2)
You may want to stick with DECIMAL but change your scale and precision.
John
"Scott" <sbailey@.mileslumber.com> wrote in message
news:O74yeO1AGHA.4080@.TK2MSFTNGP14.phx.gbl...
> Below is a sniplet of a select expression that returns a decimal number
> like .6153329998
> The result is correct, but when I say FormatPercent(objRS("myPercent"),3)
> in ASP, I get a type mismatch error.
> Both myField1 and myField2 are integer type. I have to CONVERT myField1
> into decimal in order to get a correct return in QA.
> Can someone suggest a better data type to convert myField1 so not only
> will myPercent render correct in QA, but also allow me to use
> FormatPercent in ASP?
>
> CODE:
> SUM(CONVERT(DECIMAL(18, 10), myField1)) / SUM(myField2) AS myPercent
>|||what would the synta be to convert to float?
"John Bell" <jbellnewsposts@.hotmail.com> wrote in message
news:ebALxS%23AGHA.808@.TK2MSFTNGP11.phx.gbl...
> Hi
> You may want to use your convert function after summing
> CONVERT(DECIMAL(18, 10), SUM(myField1))/ SUM(myField2)
> You may want to stick with DECIMAL but change your scale and precision.
> John
> "Scott" <sbailey@.mileslumber.com> wrote in message
> news:O74yeO1AGHA.4080@.TK2MSFTNGP14.phx.gbl...
>|||Hi
The same but use float as the data type, the syntax for convert is described
in Books online as:
CONVERT ( data_type [ ( length ) ] , expression [ , style ] )
John
"Scott" <sbailey@.mileslumber.com> wrote in message
news:eEj4bU$AGHA.3840@.TK2MSFTNGP15.phx.gbl...
> what would the synta be to convert to float?
>
> "John Bell" <jbellnewsposts@.hotmail.com> wrote in message
> news:ebALxS%23AGHA.808@.TK2MSFTNGP11.phx.gbl...
>