Thursday, March 29, 2012
Cursor versus While Loop
Thanks!!The short answer boils down to both options are bad, and you are correct that the WHILE/SELECT/DELETE choice is even worse than the cursor.
More than 99 percent of the time there is a set-based solution that is hundreds or thousands of times faster/better than any loop can be, so the set based solution is what should be your "holy grail". Fix the problem instead of trying to find ways to make the loop less of an annoyance!
-PatP|||Why don't you post what it is you're trying to dosql
Cursor to populate a table
I am trying to create a cursor (please see the code below) that will
populate client_all table that has two columns clientid and cid.
The first value for that table is drawn from TClient table (@.clientid)
and the second one is drawn from get_client_all function (cid).
I have to populate client_all table until I reach the end of Tclient
table. Tclient table has about 16000 rows. Each of @.clientID might
have multiple cids. This cursor runs a long time and doesn't
complete.
Anybody has any idea?
Thanks,
declare @.rownumber int
declare @.rowcount int
select @.rowcount = count(*) from tciclien
Declare PopulateTable_cursor Cursor for
select idnumber from TClient
open PopulateTable_cursor
declare @.clientid int
Fetch Next from PopulateTable_cursor
Into @.clientid
WHILE @.@.FETCH_STATUS <> -1
Begin
while @.rownumber < = @.rowcount
Begin
insert into Client_all
select @.clientid, cd.cid
from get_client_all(@.clientid, -1, 0) cd
End
End
close PopulateTable_cursor
deallocate PopulateTable_cursor
On Jul 5, 6:26 pm, "Will Alber" <j...@.crazy-pug.co.uk> wrote:[vbcol=seagreen]
> What does get_client_all do? Can you move away from using cursors and
> instead just join TClient against the equivalent of whatever this function
> returns?
> "tolcis" <nytolly...@.gmail.com> wrote in message
> news:1183670562.499319.150460@.n60g2000hse.googlegr oups.com...
>
>
That function loop through different table to gather sub clients. The
function returns a temp table.
Thanks,
|||On Jul 6, 5:41 am, tolcis <nytolly...@.gmail.com> wrote:
> On Jul 5, 6:26 pm, "Will Alber" <j...@.crazy-pug.co.uk> wrote:
>
>
>
>
>
>
> That function loop through different table to gather sub clients. The
> function returns a temp table.
> Thanks,- Hide quoted text -
> - Show quoted text -
Can you post the code for get_client_all? How exactly are you
'looping' through? More cursors?
Cursor to populate a table
I am trying to create a cursor (please see the code below) that will
populate client_all table that has two columns clientid and cid.
The first value for that table is drawn from TClient table (@.clientid)
and the second one is drawn from get_client_all function (cid).
I have to populate client_all table until I reach the end of Tclient
table. Tclient table has about 16000 rows. Each of @.clientID might
have multiple cids. This cursor runs a long time and doesn't
complete.
Anybody has any idea?
Thanks,
declare @.rownumber int
declare @.rowcount int
select @.rowcount = count(*) from tciclien
Declare PopulateTable_cursor Cursor for
select idnumber from TClient
open PopulateTable_cursor
declare @.clientid int
Fetch Next from PopulateTable_cursor
Into @.clientid
WHILE @.@.FETCH_STATUS <> -1
Begin
while @.rownumber < = @.rowcount
Begin
insert into Client_all
select @.clientid, cd.cid
from get_client_all(@.clientid, -1, 0) cd
End
End
close PopulateTable_cursor
deallocate PopulateTable_cursorWhat does get_client_all do? Can you move away from using cursors and
instead just join TClient against the equivalent of whatever this function
returns?
"tolcis" <nytollydba@.gmail.com> wrote in message
news:1183670562.499319.150460@.n60g2000hse.googlegroups.com...
> Hi!
> I am trying to create a cursor (please see the code below) that will
> populate client_all table that has two columns clientid and cid.
> The first value for that table is drawn from TClient table (@.clientid)
> and the second one is drawn from get_client_all function (cid).
> I have to populate client_all table until I reach the end of Tclient
> table. Tclient table has about 16000 rows. Each of @.clientID might
> have multiple cids. This cursor runs a long time and doesn't
> complete.
> Anybody has any idea?
> Thanks,
>
> declare @.rownumber int
> declare @.rowcount int
> select @.rowcount = count(*) from tciclien
> Declare PopulateTable_cursor Cursor for
> select idnumber from TClient
> open PopulateTable_cursor
> declare @.clientid int
> Fetch Next from PopulateTable_cursor
> Into @.clientid
> WHILE @.@.FETCH_STATUS <> -1
> Begin
> while @.rownumber < = @.rowcount
> Begin
> insert into Client_all
> select @.clientid, cd.cid
> from get_client_all(@.clientid, -1, 0) cd
> End
> End
> close PopulateTable_cursor
> deallocate PopulateTable_cursor
>|||On Jul 5, 6:26 pm, "Will Alber" <j...@.crazy-pug.co.uk> wrote:[vbcol=seagreen]
> What does get_client_all do? Can you move away from using cursors and
> instead just join TClient against the equivalent of whatever this function
> returns?
> "tolcis" <nytolly...@.gmail.com> wrote in message
> news:1183670562.499319.150460@.n60g2000hse.googlegroups.com...
>
>
>
>
>
That function loop through different table to gather sub clients. The
function returns a temp table.
Thanks,|||"tolcis" <nytollydba@.gmail.com> wrote in message
news:1183678877.263066.236090@.o61g2000hsh.googlegroups.com...
> On Jul 5, 6:26 pm, "Will Alber" <j...@.crazy-pug.co.uk> wrote:
> That function loop through different table to gather sub clients. The
> function returns a temp table.
>
Then I can only say that this looks like a classic case of how NOT to write
SQL. You should start with a set-based approach to every problem. Only
resort to cursors and loops in very exceptional cases. If you aren't sure
you can do that then get into the habit of seeking a second opinion before
you write a cursor. Your code will be much simpler and more efficient that
way.
If you need more help, please post DDL, sample data and show your required
end result.
David Portas, SQL Server MVP
Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.
SQL Server Books Online:
http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
--|||On Jul 6, 5:41 am, tolcis <nytolly...@.gmail.com> wrote:
> On Jul 5, 6:26 pm, "Will Alber" <j...@.crazy-pug.co.uk> wrote:
>
>
>
>
>
>
>
>
>
>
> That function loop through different table to gather sub clients. The
> function returns a temp table.
> Thanks,- Hide quoted text -
> - Show quoted text -
Can you post the code for get_client_all? How exactly are you
'looping' through? More cursors?
Cursor to populate a table
I am trying to create a cursor (please see the code below) that will
populate client_all table that has two columns clientid and cid.
The first value for that table is drawn from TClient table (@.clientid)
and the second one is drawn from get_client_all function (cid).
I have to populate client_all table until I reach the end of Tclient
table. Tclient table has about 16000 rows. Each of @.clientID might
have multiple cids. This cursor runs a long time and doesn't
complete.
Anybody has any idea?
Thanks,
declare @.rownumber int
declare @.rowcount int
select @.rowcount = count(*) from tciclien
Declare PopulateTable_cursor Cursor for
select idnumber from TClient
open PopulateTable_cursor
declare @.clientid int
Fetch Next from PopulateTable_cursor
Into @.clientid
WHILE @.@.FETCH_STATUS <> -1
Begin
while @.rownumber < = @.rowcount
Begin
insert into Client_all
select @.clientid, cd.cid
from get_client_all(@.clientid, -1, 0) cd
End
End
close PopulateTable_cursor
deallocate PopulateTable_cursorWhat does get_client_all do? Can you move away from using cursors and
instead just join TClient against the equivalent of whatever this function
returns?
"tolcis" <nytollydba@.gmail.com> wrote in message
news:1183670562.499319.150460@.n60g2000hse.googlegroups.com...
> Hi!
> I am trying to create a cursor (please see the code below) that will
> populate client_all table that has two columns clientid and cid.
> The first value for that table is drawn from TClient table (@.clientid)
> and the second one is drawn from get_client_all function (cid).
> I have to populate client_all table until I reach the end of Tclient
> table. Tclient table has about 16000 rows. Each of @.clientID might
> have multiple cids. This cursor runs a long time and doesn't
> complete.
> Anybody has any idea?
> Thanks,
>
> declare @.rownumber int
> declare @.rowcount int
> select @.rowcount = count(*) from tciclien
> Declare PopulateTable_cursor Cursor for
> select idnumber from TClient
> open PopulateTable_cursor
> declare @.clientid int
> Fetch Next from PopulateTable_cursor
> Into @.clientid
> WHILE @.@.FETCH_STATUS <> -1
> Begin
> while @.rownumber < = @.rowcount
> Begin
> insert into Client_all
> select @.clientid, cd.cid
> from get_client_all(@.clientid, -1, 0) cd
> End
> End
> close PopulateTable_cursor
> deallocate PopulateTable_cursor
>|||On Jul 5, 6:26 pm, "Will Alber" <j...@.crazy-pug.co.uk> wrote:
> What does get_client_all do? Can you move away from using cursors and
> instead just join TClient against the equivalent of whatever this function
> returns?
> "tolcis" <nytolly...@.gmail.com> wrote in message
> news:1183670562.499319.150460@.n60g2000hse.googlegroups.com...
> > Hi!
> > I am trying to create a cursor (please see the code below) that will
> > populate client_all table that has two columns clientid and cid.
> > The first value for that table is drawn from TClient table (@.clientid)
> > and the second one is drawn from get_client_all function (cid).
> > I have to populate client_all table until I reach the end of Tclient
> > table. Tclient table has about 16000 rows. Each of @.clientID might
> > have multiple cids. This cursor runs a long time and doesn't
> > complete.
> > Anybody has any idea?
> > Thanks,
> > declare @.rownumber int
> > declare @.rowcount int
> > select @.rowcount = count(*) from tciclien
> > Declare PopulateTable_cursor Cursor for
> > select idnumber from TClient
> > open PopulateTable_cursor
> > declare @.clientid int
> > Fetch Next from PopulateTable_cursor
> > Into @.clientid
> > WHILE @.@.FETCH_STATUS <> -1
> > Begin
> > while @.rownumber < = @.rowcount
> > Begin
> > insert into Client_all
> > select @.clientid, cd.cid
> > from get_client_all(@.clientid, -1, 0) cd
> > End
> > End
> > close PopulateTable_cursor
> > deallocate PopulateTable_cursor
That function loop through different table to gather sub clients. The
function returns a temp table.
Thanks,|||"tolcis" <nytollydba@.gmail.com> wrote in message
news:1183678877.263066.236090@.o61g2000hsh.googlegroups.com...
> On Jul 5, 6:26 pm, "Will Alber" <j...@.crazy-pug.co.uk> wrote:
>> What does get_client_all do? Can you move away from using cursors and
>> instead just join TClient against the equivalent of whatever this
>> function
>> returns?
> That function loop through different table to gather sub clients. The
> function returns a temp table.
>
Then I can only say that this looks like a classic case of how NOT to write
SQL. You should start with a set-based approach to every problem. Only
resort to cursors and loops in very exceptional cases. If you aren't sure
you can do that then get into the habit of seeking a second opinion before
you write a cursor. Your code will be much simpler and more efficient that
way.
If you need more help, please post DDL, sample data and show your required
end result.
--
David Portas, SQL Server MVP
Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.
SQL Server Books Online:
http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
--|||On Jul 6, 5:41 am, tolcis <nytolly...@.gmail.com> wrote:
> On Jul 5, 6:26 pm, "Will Alber" <j...@.crazy-pug.co.uk> wrote:
>
>
> > What does get_client_all do? Can you move away from using cursors and
> > instead just join TClient against the equivalent of whatever this function
> > returns?
> > "tolcis" <nytolly...@.gmail.com> wrote in message
> >news:1183670562.499319.150460@.n60g2000hse.googlegroups.com...
> > > Hi!
> > > I am trying to create a cursor (please see the code below) that will
> > > populate client_all table that has two columns clientid and cid.
> > > The first value for that table is drawn from TClient table (@.clientid)
> > > and the second one is drawn from get_client_all function (cid).
> > > I have to populate client_all table until I reach the end of Tclient
> > > table. Tclient table has about 16000 rows. Each of @.clientID might
> > > have multiple cids. This cursor runs a long time and doesn't
> > > complete.
> > > Anybody has any idea?
> > > Thanks,
> > > declare @.rownumber int
> > > declare @.rowcount int
> > > select @.rowcount = count(*) from tciclien
> > > Declare PopulateTable_cursor Cursor for
> > > select idnumber from TClient
> > > open PopulateTable_cursor
> > > declare @.clientid int
> > > Fetch Next from PopulateTable_cursor
> > > Into @.clientid
> > > WHILE @.@.FETCH_STATUS <> -1
> > > Begin
> > > while @.rownumber < = @.rowcount
> > > Begin
> > > insert into Client_all
> > > select @.clientid, cd.cid
> > > from get_client_all(@.clientid, -1, 0) cd
> > > End
> > > End
> > > close PopulateTable_cursor
> > > deallocate PopulateTable_cursor
> That function loop through different table to gather sub clients. The
> function returns a temp table.
> Thanks,- Hide quoted text -
> - Show quoted text -
Can you post the code for get_client_all? How exactly are you
'looping' through? More cursors?
Tuesday, March 27, 2012
Cursor issues
I can get it to create the proc, but it dosen't replace the variable or loop through the select list from ziptrendindex.
Any ideas on what I'm missing?
declare @.countyname varchar (200)
declare @.sql varchar(8000)
declare county_name cursor for
select distinct county from ZipTrendIndex
open county_name
fetch next from county_name
into @.countyname
WHILE @.@.FETCH_STATUS = 0
BEGIN
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[county'+@.countyname+']') AND type in (N'U'))
BEGIN
set @.sql = 'CREATE PROCEDURE dbo.getUpdRecords AS
SET NOCOUNT ON
Declare @.PropertyID bigint
Declare @.PropertyIDBuffer bigint
Declare @.AVMValue float
Declare @.Confidence float
Declare @.a bigint
Declare @.b smallint
Set @.a = 1
Set @.b = 0
While (@.a) > 0
Begin
Select top 1 @.PropertyIDBuffer = sa_property_id from county_name (NOLOCK) Where replyavm is null
If @.PropertyIDBuffer is not null Or @.PropertyIDBuffer > 0
Begin
Set @.b = 0
DECLARE Property_Details CURSOR FOR
Select top 50 sa_property_id
From county_name (NOLOCK)
Where replyavm is null
OPEN Property_Details
FETCH NEXT FROM Property_Details
INTO @.PropertyID
WHILE @.@.FETCH_STATUS = 0
BEGIN
Set @.AVMValue = 0
Set @.Confidence = 0
exec usp_ReplyAVMCalculationcounty_name @.PropertyID, @.AVMValue output, @.Confidence output
If @.AVMValue is Null
Begin
Set @.AVMValue = 0
Set @.Confidence = 0
End
Update county_name
Set ReplyAVM = @.AVMValue,
ReplyScore = @.Confidence
Where sa_property_id = @.PropertyID
FETCH NEXT FROM Property_Details
INTO @.PropertyID
END
CLOSE Property_Details
DEALLOCATE Property_Details
End
Else
Set @.a = 0
End
SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
'
exec (@.sql)
end
fetch next from county_name into @.countyname
end
CLOSE county_name
DEALLOCATE county_name
One quick look and I found you are not setting @.sql to '' while looking through.
exec (@.sql)
end
SET @.sql = ''
fetch next from county_name into @.countyname
end
|||Thanks!!
That did the trick!!
Sunday, March 25, 2012
Cursor from stored procedure?
procedure, so basically something like this...
DECLARE @.proc varchar(250)
Set @.proc = '[' + @.DBServerName + '].thedb.dbo.spGetBCXDiags ' +
Cast(@.LastUpdateDate As Varchar(7))
DECLARE the_cursor CURSOR FOR @.proc
SQL Server expects a 'Select' statement instead of an SP name and therefore
is giving me an error. I am building the stored procedure name to include
the server name because I am linking with the @.DBServerName server before
this statement (with sp_addlinkedserver).
I tried just issuing a built 'Select' statement against the linked server,
but again, the 'Select' statement had to be built as a string to include the
linked server name. Is there a Transact-SQL version of eval() or something
like that to tell it to treat the string version of the 'Select' statement a
s
if it were a 'Select' statement that was just typed in (not built as a
string)? Or, is there a way to build a cursor by defining it to be a stored
procedure instead of a 'Select' statement? Seems as though I'm in a catch-2
2
unless I'm missing something.
Thanks,
ToddI dont think you can define based directly on a SP.
Instead, store the results in a Temp table and base your cursor on the temp
table.
Gopi
"Todd Bright" <ToddBright@.discussions.microsoft.com> wrote in message
news:AB4C0DE3-DC07-4BFB-99AB-EB10320B37FF@.microsoft.com...
>I have a situation where I need to create a cursor based on a stored
> procedure, so basically something like this...
> DECLARE @.proc varchar(250)
> Set @.proc = '[' + @.DBServerName + '].thedb.dbo.spGetBCXDiags ' +
> Cast(@.LastUpdateDate As Varchar(7))
> DECLARE the_cursor CURSOR FOR @.proc
> SQL Server expects a 'Select' statement instead of an SP name and
> therefore
> is giving me an error. I am building the stored procedure name to include
> the server name because I am linking with the @.DBServerName server before
> this statement (with sp_addlinkedserver).
> I tried just issuing a built 'Select' statement against the linked server,
> but again, the 'Select' statement had to be built as a string to include
> the
> linked server name. Is there a Transact-SQL version of eval() or
> something
> like that to tell it to treat the string version of the 'Select' statement
> as
> if it were a 'Select' statement that was just typed in (not built as a
> string)? Or, is there a way to build a cursor by defining it to be a
> stored
> procedure instead of a 'Select' statement? Seems as though I'm in a
> catch-22
> unless I'm missing something.
> Thanks,
> Todd|||The problem is that I have to build a string that represents the remote
stored procedure or string that represents a 'Select' statement. I must
build the string representations in order to dynamically include the remotel
y
linked server name into the equation. If I build a string representation of
an SP SQL Server will run it, but I have no way of seeing the records it
returns that I know of (can't build a cursor from an SP). If I build a
string representation of a 'Select' statement that includes the remote serve
r
name, how the heck do you tell SQL Server to run the 'Select'? It's just a
string value to SQL Server.
I guess my other options are to have a separate SP for each server I'm going
to link to or to put the code on each SQL Server machine and link back up
with the main server. That way the linked server name will be constant. I
didn't want to do either of these unless, of course, the other way just won'
t
work.
"rgn" wrote:
> I dont think you can define based directly on a SP.
> Instead, store the results in a Temp table and base your cursor on the tem
p
> table.
> Gopi
> "Todd Bright" <ToddBright@.discussions.microsoft.com> wrote in message
> news:AB4C0DE3-DC07-4BFB-99AB-EB10320B37FF@.microsoft.com...
>
>sql
Cursor Based SQL?
based SQL writing? I have to create SQL that can loop though records
simular to VB loops and I have been told that this is the way to go.
Any recommendations would be helpful.Philip Mette wrote:
> Does anyone have any good references they could recommend on Cursor
> based SQL writing? I have to create SQL that can loop though records
> simular to VB loops and I have been told that this is the way to go.
> Any recommendations would be helpful.
Don't listen to Java/C#/VB/<insert proc language of your choice> developers.
cursors and SQL are mutually exclusive.
A cursor is a way to interface SQL to procedural languages.
Cheers
Serge|||"Philip Mette" <philipdm@.msn.com> wrote in message
news:96a56e66.0408250626.f768f9b@.posting.google.co m...
> Does anyone have any good references they could recommend on Cursor
> based SQL writing? I have to create SQL that can loop though records
> simular to VB loops and I have been told that this is the way to go.
> Any recommendations would be helpful.
You should never use a cursor unless there is no other possible solution -
TSQL is a set-based language, and MSSQL is heavily optimized to run
set-based code. Cursors are extremely slow, and they are not often
required - if you can give more details of what you're trying to do, someone
may be able to suggest a set-based approach.
If you do post more information, please include CREATE TABLE statements,
INSERTs for sample data, and sample output to make it easier to understand
what you're doing.
Simon|||On 25 Aug 2004 07:26:50 -0700, Philip Mette wrote:
>Does anyone have any good references they could recommend on Cursor
>based SQL writing? I have to create SQL that can loop though records
>simular to VB loops and I have been told that this is the way to go.
>Any recommendations would be helpful.
Hi Philip,
Why do you think that you have to create SQL that can loop through rows
(not records!!)? About 95% of the times that someone thinks that looping
is the only way to solve a problem, it isn't. And a set-based solution is
faster than a cursor in 99.9% of these situations.
Why don't you post some more info about the problem you're trying to solve
instead of focussing on a (probably sub-optimal) choice of how to solve
it. Chances are that someone will help you find a set-based solution to
your problem.
The best way to post a problem is by supplying the table structure (as
copy-and-pasteable CREATE TABLE statements, including constraints), sample
data (as copy-and-pastteable INSERT statements) and expected output along
with a description of the business problem you're trying to solve and (if
you have it) your current SQL. http://www.aspfaq.com/etiquette.asp?id=5006
and http://vyaskn.tripod.com/code.htm#inserts provide some help on putting
together the information for a good posting.
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)|||Philip Mette (philipdm@.msn.com) writes:
> Does anyone have any good references they could recommend on Cursor
> based SQL writing? I have to create SQL that can loop though records
> simular to VB loops and I have been told that this is the way to go.
> Any recommendations would be helpful.
Here is a quick example which says everything you need to know:
create procedure TSQL_ProductProc (@.product int output)
as
begin
declare @.sales int
declare c INSENSITIVE cursor for select intcolumn from tbl
open c
set @.product = NULL
while 1 = 1
begin
fetch next from c into @.sales
IF @.@.fetch_status <> 0
BREAK
set @.product = coalesce(@.product, 1) * @.sales
end
close c
deallocate c
end
Notes:
1) Always make cursors INENSITIVE. The default keyset cursor is
incomprehensible, to me at least, and has given me more than one bad
negative performance surprise. (Might have happened more in SQL 6.5.)
2) By putting the FETCH statement first in the loop, the code does not
only get shorter, it is also easier to maintain. If you have two
FETCH statements, and one is at the end of a long loop, you can
easily forget to augment that statement if you add another column
to the cursor, giving difficult-to-find errors, since the cursors
works on the first iteration in the loop.
Incidently, this example is a case a cursor might be necessary, as
there is no way to do this sort of thing in a set-based statment.
(You can use SUM with LOG and EXP for a product, if you only have
positive values, but not in the general case.)
As others have pointed out, cursors should only be used as a last
resort. First try to find a set-based way of attacking the problem.
For a large data set, the difference in performance may several
magnitudes.
But using cursors can sometimes cut development time considerably.
Say that you have a stored procedure that performs the task you
want to do on a set of scalar values received as parameters. Writing
a cursor loop which calls that procedure is a simple task. Rewriting
the stored procedure to handle an input set, may be a major undertaking.
And if you know that you the data set you will loop over will be modest
in size, it may simply not be worth the cost.
--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||Erland Sommarskog <esquel@.sommarskog.se> wrote in message news:<Xns9550F208A313CYazorman@.127.0.0.1>...
> Philip Mette (philipdm@.msn.com) writes:
> > Does anyone have any good references they could recommend on Cursor
> > based SQL writing? I have to create SQL that can loop though records
> > simular to VB loops and I have been told that this is the way to go.
> > Any recommendations would be helpful.
> Here is a quick example which says everything you need to know:
> create procedure TSQL_ProductProc (@.product int output)
> as
> begin
> declare @.sales int
> declare c INSENSITIVE cursor for select intcolumn from tbl
> open c
> set @.product = NULL
> while 1 = 1
> begin
> fetch next from c into @.sales
> IF @.@.fetch_status <> 0
> BREAK
> set @.product = coalesce(@.product, 1) * @.sales
> end
> close c
> deallocate c
> end
> Notes:
> 1) Always make cursors INENSITIVE. The default keyset cursor is
> incomprehensible, to me at least, and has given me more than one bad
> negative performance surprise. (Might have happened more in SQL 6.5.)
> 2) By putting the FETCH statement first in the loop, the code does not
> only get shorter, it is also easier to maintain. If you have two
> FETCH statements, and one is at the end of a long loop, you can
> easily forget to augment that statement if you add another column
> to the cursor, giving difficult-to-find errors, since the cursors
> works on the first iteration in the loop.
> Incidently, this example is a case a cursor might be necessary, as
> there is no way to do this sort of thing in a set-based statment.
> (You can use SUM with LOG and EXP for a product, if you only have
> positive values, but not in the general case.)
> As others have pointed out, cursors should only be used as a last
> resort. First try to find a set-based way of attacking the problem.
> For a large data set, the difference in performance may several
> magnitudes.
> But using cursors can sometimes cut development time considerably.
> Say that you have a stored procedure that performs the task you
> want to do on a set of scalar values received as parameters. Writing
> a cursor loop which calls that procedure is a simple task. Rewriting
> the stored procedure to handle an input set, may be a major undertaking.
> And if you know that you the data set you will loop over will be modest
> in size, it may simply not be worth the cost.
--Ok I will send you the table and fields names along with the psuedo
logic of what i need done to get you started since you ask.:) I will
send the create table and data statements soon. Here is what I need.
A collector takes or makes calls. During this call he gets a PTP or
promise to pay. This activity is stored in tblDailyActivities and the
activity status is 'OP' or Open by default. In another table,
tblDailyPayments store payments that have come in through out the
month.
Here are the tables:
tblDailyActivities
Record_Key_Num
Acct_Num
Activity_Date (Date Promise to Pay Was Made)
Promise_Amt_1
Due_Date (Date Next Payment Is Due)
Promise_Status
Total_Dollars_Coll
tblDailyPayments
Record_Key_Num
Acct_Num
Pay_Amt
Activity_Date (Date Payment Was Made)
Here is the logic.(Keep in mind that their can be more than one
promise made on same acct by the same or different collector so the
logic is handling this, you will see.)
For Each [Acct_Num and Due_Date] combination
Look for payments from the tblDailyPayments Table with an
activity_date that are within tblDailyActivites.Activity_Date + 10
days.
If the sum of Payments>=90% of
tblDailyActivities.Promise_Amt_1 then
Update tblDailyActivities.Promise_Status =
'PK' and tblDailyActivites.Total_Dollars_Coll= 'Sum (of Payments)'
And all other same [Acct_Num and Due_Date]
combination's update tblDailyActivities.Promise_Status = 'IP'
Else If the sum of Payments<90% of
tblDailyActivities.Promise_Amt_1, then
If tblDailyActivites.Activity_Date +10 days > today's date, then
tblDailyActivities.Promise_Status= 'OP' and exit loop
Else If tblCacsDailyActivites.Activity_Date +10 days < today's
date, then
Update tblCacsDailyActivities.Promise_Status = 'PB'
And move to record 2 of same [Acct_Num and Due_Date] combination.
And repeat until end of loop.
HERES SOME DATA SAMPLE:
TBLDAILYACTIVITIES
RecKey Account ActivityDate DueDate UserId PromiseAMt PromiseDate
PromiseStatus TotalColl
688849733934408/06/200408/30/2004MPJ5 525.00 08/16/2004
OP <Null>
688850733934408/07/200408/30/2004MPJ5 525.00 09/15/2004
OP <Null
688851733934408/20/200409/30/2004MPLI 600.00 09/15/2004
OP <Null>
688852733934408/21/200409/30/2004MPLT 700.00 10/15/2004
OP <Null
688853611665508/12/200408/30/2004MP60 500.00 09/15/2004
OP <Null>
688854611665508/12/200408/30/2004MP61 550.00 09/15/2004
OP <Null
TBLDAILY PAYMENTS
RecKey Account PayAmt ActivityDate
1254 7339344 225.00 08/10/2004
1255 7339344 295.00 08/11/2004
1259 7339344 300.00 08/20/2004
1354 6116655 250.00 08/13/2004
OUTPUT
RecKey Account ActivityDate DueDate UserId PromiseAMt PromiseDate
PromiseStatus TotalColl
688849733934408/06/200408/30/2004MPJ5 525.00 08/16/2004
PK 520.00
688850733934408/06/200408/30/2004MPJ5 525.00 09/15/2004
IP <Null
688851733934408/20/200409/30/2004MPLI 525.00 09/15/2004
OP 300.00
688852733934408/21/200409/30/2004MPLT 525.00 10/15/2004
IP <Null
688853611665508/12/200408/30/2004MP60 500.00 09/15/2004
PB 250.00
688854611665508/12/200408/30/2004MP61 550.00 09/15/2004
IP <Null
THE FIRST TABLE REPRESENTS ACTIVITIES THE SECOUND PAYMENTS THAT COME
IN.
THE 3RD IS HOW THE DATA SHOULD LOOK. THIS IS BASED OFF OF ACCT AND
DUEDATE COMBINATIONS SO THE LOOP
WILL STARTS OVER ON THE SAME ACCT IF THE DUEDATE CHANGES. SINCE THE
2ND GROUP OF RECORDS STILL
IS IN THE 10 DAY WINDOW FROM ACTIVITY DATE TO TODAY WE KEEP IT OPEN
EVEN THOUGH THE AMOUNT IS LESS THAN 90%.
BECAUSE THEY HAVE A FEW MORE DAYS TO GET MORE PAYMENTS IN TO MAKE THIS
A PK. THE GOAL IS TO GET THE FIRST RECORD OF A
ACCT DUEDATE GROUP MARK IT EITHER PK OR PB AND MOVE TO THE NEXT UNTILL
YOU FIND A PK ONCE A PK IS FOUND MARK ALL OTHERS WITH
IN THAT GROUP IP. TOTAL DOLLARS IS ONLY RECORDED IN PK OP AND PB.
If this can be done without cursors I will be very thankful. You all
out on the posting boards have been great. Thanks so much for all your
assistance. You make SQL coding exciting.|||Erland Sommarskog <esquel@.sommarskog.se> wrote in message news:<Xns9550F208A313CYazorman@.127.0.0.1>...
> Philip Mette (philipdm@.msn.com) writes:
> > Does anyone have any good references they could recommend on Cursor
> > based SQL writing? I have to create SQL that can loop though records
> > simular to VB loops and I have been told that this is the way to go.
> > Any recommendations would be helpful.
> Here is a quick example which says everything you need to know:
> create procedure TSQL_ProductProc (@.product int output)
> as
> begin
> declare @.sales int
> declare c INSENSITIVE cursor for select intcolumn from tbl
> open c
> set @.product = NULL
> while 1 = 1
> begin
> fetch next from c into @.sales
> IF @.@.fetch_status <> 0
> BREAK
> set @.product = coalesce(@.product, 1) * @.sales
> end
> close c
> deallocate c
> end
> Notes:
> 1) Always make cursors INENSITIVE. The default keyset cursor is
> incomprehensible, to me at least, and has given me more than one bad
> negative performance surprise. (Might have happened more in SQL 6.5.)
> 2) By putting the FETCH statement first in the loop, the code does not
> only get shorter, it is also easier to maintain. If you have two
> FETCH statements, and one is at the end of a long loop, you can
> easily forget to augment that statement if you add another column
> to the cursor, giving difficult-to-find errors, since the cursors
> works on the first iteration in the loop.
> Incidently, this example is a case a cursor might be necessary, as
> there is no way to do this sort of thing in a set-based statment.
> (You can use SUM with LOG and EXP for a product, if you only have
> positive values, but not in the general case.)
> As others have pointed out, cursors should only be used as a last
> resort. First try to find a set-based way of attacking the problem.
> For a large data set, the difference in performance may several
> magnitudes.
> But using cursors can sometimes cut development time considerably.
> Say that you have a stored procedure that performs the task you
> want to do on a set of scalar values received as parameters. Writing
> a cursor loop which calls that procedure is a simple task. Rewriting
> the stored procedure to handle an input set, may be a major undertaking.
> And if you know that you the data set you will loop over will be modest
> in size, it may simply not be worth the cost.
Ok I realize my last post was probably difficult to follow so mabye
someone can interpret this. I know how to write what I want in Oracle
SQL can someone convert it for me . I do not know MS SQL enough to
make the change.
Here is the code:
CREATE OR REPLACE PROCEDURE UPD_ACTIVITY IS
CURSOR ACT_cur1
IS
SELECT DISTINCT A.ACCT_NUM, A.ACTIVITY_DATE
FROM TBLCACSDAILYACTIVITIES A ; /* this picks the unique
combination of acct and date*/
tot_pay number ;
rec_upd varchar2(1);
todays_date date;
BEGIN
dbms_output.put_line('inside upd_activity ');
SELECT SYSDATE INTO todays_date FROM DUAL;
FOR ACT_CUR_REC1 IN ACT_CUR1
LOOP
rec_upd := 'N';
DECLARE
CURSOR ACT_CUR2 IS
SELECT B.ACCT_NUM,
B.ACTIVITY_DATE,B.PROMISE_AMT_1,B.PROMISE_STATUS,
B.TOTAL_DOLLARS_COLL
FROM TBLCACSDAILYACTIVITIES B
WHERE B.ACCT_NUM = ACT_CUR_REC1.ACCT_NUM
AND B.ACTIVITY_DATE = ACT_CUR_REC1.ACTIVITY_DATE
ORDER BY B.ACTIVITY_DATE
FOR UPDATE OF B.PROMISE_STATUS,B.TOTAL_DOLLARS_COLL
NOWAIT;
BEGIN
dbms_output.put_line('inside upd_activity1111 ');
FOR ACT_CUR_REC2 IN ACT_CUR2
LOOP
BEGIN
SELECT SUM(C.PAY_AMT) into tot_pay
FROM TBLCACSDAILYPAYMENTS C
WHERE C.ACCT_NUM = ACT_CUR_REC2.ACCT_NUM
AND C.ACTIVITY_DATE >= ACT_CUR_REC2.ACTIVITY_DATE
AND C.ACTIVITY_DATE < ACT_CUR_REC2.ACTIVITY_DATE+10;
dbms_output.put_line('tot_pay =');
IF tot_pay >= .9 * ACT_CUR_REC2.PROMISE_AMT_1 THEN
IF rec_upd = 'N' THEN /* recs have not bee updated for promise
status*/
UPDATE TBLCACSDAILYACTIVITIES
SET PROMISE_STATUS = 'PK',
TOTAL_DOLLARS_COLL = tot_pay
WHERE CURRENT OF ACT_CUR2;
rec_upd := 'Y';
ELSIF rec_upd = 'Y' THEN
UPDATE TBLCACSDAILYACTIVITIES
SET PROMISE_STATUS = 'IP'
WHERE CURRENT OF ACT_CUR2;
END IF;
ELSIF tot_pay < .9 * ACT_CUR_REC2.PROMISE_AMT_1 THEN
IF (ACT_CUR_REC2.ACTIVITY_DATE+10) > todays_date THEN
UPDATE TBLCACSDAILYACTIVITIES
SET PROMISE_STATUS = 'OP'
WHERE CURRENT OF ACT_CUR2;
ELSE
UPDATE TBLCACSDAILYACTIVITIES
SET PROMISE_STATUS = 'PB'
WHERE CURRENT OF ACT_CUR2;
END IF;
END IF;
END;
END LOOP; /* end of ACT_CUR_REC2 loop */
END;
END LOOP; /*end of ACT_CUR_REC1 */
END ; /* end of proc */
/
Thanks again!|||Philip Mette (philipdm@.msn.com) writes:
> --Ok I will send you the table and fields names along with the psuedo
> logic of what i need done to get you started since you ask.:) I will
> send the create table and data statements soon. Here is what I need.
Yes, this appears to be doable with set-based statements, an outline
follows. Had you included your tables and data with CREATE TABLE and
INSERT statements, I would have been able to test my solution.
I also need to insert the disclaimer that I don't think I understand
the business requirements completely. The algorithm indeeds looks funny
to me. What if for the first two rows there are payments for the first
promise? What if there are payments that match more than one combination?
And there is a contradiction between verbal description and the Oracle
code you posted. The narrative says account/duedate, but the Oracle
code does not touch duedate. ActivityDate appears to better macthc results.
-- First we need some extra columns to play with, so we move to a temp
-- table. Here create with SELECT INTO to save some typing.
SELECT *, isfirst = convert(bit, 0) INTO #t FROM TBLCACSDAILYACTIVITIES
-- Set is first bit.
UPDATE #t
SET isfirst = 1
FROM #t
JOIN (SELECT RecKey = MIN(RecKey)
FROM #t
GROUP BY Account, ActivityDate) AS c
ON #t.RecKey = c.RecKey
-- Set totals.
UPDATE #t
SET TotalColl = p.payamt
FROM #t t
JOIN (SELECT t.Account, t.ActivityDate, payamt = SUM(t.Payment)
FROM #t
JOIN dailypayments d
ON t.account = p.account
AND p.ActivityDate BETWEEN t.ActivityDate AND t.ActivityDate + 10
GROUP BY t.account, t.ActivtithDate) AS s
ON t.Account = s.Account
AND t.AcctivityDate = s.ActivityDate
-- Now clear total where we should save, and set status
UPDATE #t
SET TotalCol1 = CASE WHEN TotalCol1 > 0.9 * PromsieAmt AND isfirst = 1
THEN TotalCol1
ELSE NULL
END,
Status = CASE WHEN TotalCol1 > 0.9 * PromsieAmt
THEN CASE isfirst WHEN 1 THEN 'PK' ELSE 'IP' END
ELSE CASE WHEN dateadd(DAY, ActivityDate, 10) >
convert(char(8), getdate(), 112)
THEN 'OP'
ELSE 'PB'
END
END
-- Final update of table left as exercise for the reader.
--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp
Thursday, March 22, 2012
Current user in SQL
Hi
Is there a variable or a possibility to use the current user in sql?
I would like to create an update trigger and write the user that made the change in the affected table!
Thanks!
Try SUSER_NAME() for the login or USER_NAME() for the database user.
|||Pick your poison ;-)
SELECT SUSER_SNAME(),USER_NAME(),CURRENT_USER
Denis The SQL Menace
http://sqlservercode.blogspot.com
http://sqlblog.com/blogs/denis_gobo/default.aspx
Monday, March 19, 2012
Current Date
effective date is less then today. Something like <NOW() or <Date(). This
has to be simple but I just can't seem to get it to work.On Jan 2, 5:14=A0pm, John <J...@.discussions.microsoft.com> wrote:
> I'm trying to create a query that will show all funds where the fund's
> effective date is less then today. =A0Something like <NOW() or <Date(). ==A0This
> has to be simple but I just can't seem to get it to work.
Depends what you are writing the query in, but in T-SQL <GETDATE() is
what you would need
Thursday, March 8, 2012
Cumulative log
Is it possible to create a cumulative log using SSIS? basiclly I have 5 logs which hold failed records. I would like to create a cumulative log and send it via email using SSIS.
thoughts?
thanks
What do you mean "cumulative"? If you use a table to store your error records, you can pull in that table and send the records in an e-mail.Though, if the records are going to be high, you may want to pull the records out to a text file and then attach that file in the Send Mail task. A better approach would be to house everything in a table and write a report against it.|||
how do you pull in different tables? via sql task? and what if you have more 1 table? you would only want to send one email with all the bad records from different tables.
|||Just create one error table. Log all of the bad records to that table and then later select from that table.|||well all tables have different structures so a single table would not work. any other ideas?
|||If you want to combine them, you are going to have to make the structures similar at some point, right? You could use a dataflow with multiple sources to combine the tables into a flat file, then email that as an attachment.|||I don't see an straight forward way to get all those rows into a single file/email. Perhaps, it may be easier to include just the key column(s); in such way the structure is the same for all the tables.
Cummulative Total
Date and Order Number to prioritize shipments by first-in-first-out.
CREATE TABLE #TMP (
DUE_DATE DATETIME,
ORD_NUM CHAR(10),
PRODUCT CHAR(3),
TONS REAL)
INSERT INTO #TMP
SELECT '2/23/07', '07026.0030', 'ABC', 3.375
UNION ALL
SELECT '2/23/07', '07047.0059', 'ABC', 3.375
UNION ALL
SELECT '2/23/07', '07053.0080', 'ABC', 3.375
UNION ALL
SELECT '2/24/07', '07045.0030', 'ABC', 2.25
UNION ALL
SELECT '2/25/07','07045.0027','ABC',1.125
UNION ALL
SELECT '2/25/07','07046.0070','ABC',6.75
SELECT T1.PRODUCT, T1.DUE_DATE, T1.ORD_NUM, T1.TONS,
'TTL_TONS'=(SELECT SUM(TONS) AS CUMM
FROM #TMP T2
WHERE T1.DUE_DATE>=T2.DUE_DATE AND T1.ORD_NUM>=T2.ORD_NUM )
FROM #TMP T1
DROP TABLE #TMP
The first 3 records returned show the right numbers in the ttl_tons column,
but then it falls apart after that?
Any hints?Maybe
CREATE TABLE #TMP (
DUE_DATE DATETIME,
ORD_NUM CHAR(10),
PRODUCT CHAR(3),
TONS REAL)
INSERT INTO #TMP
SELECT '20070223', '07026.0030', 'ABC', 3.375
UNION ALL
SELECT '20070223', '07047.0059', 'ABC', 3.375
UNION ALL
SELECT '20070223', '07053.0080', 'ABC', 3.375
UNION ALL
SELECT '20070224', '07045.0030', 'ABC', 2.25
UNION ALL
SELECT '20070225','07045.0027','ABC',1.125
UNION ALL
SELECT '20070225','07046.0070','ABC',6.75
SELECT T1.PRODUCT
, T1.DUE_DATE
, T1.ORD_NUM
, T1.TONS
, 'TTL_TONS'=(SELECT SUM(TONS) AS CUMM
FROM #TMP T2
WHERE T1.DUE_DATE>=T2.DUE_DATE
AND T1.ORD_NUM >= CASE
WHEN T1.DUE_DATE=T2.DUE_DATE THEN
T2.ORD_NUM
ELSE
T1.ORD_NUM
END)
FROM #TMP T1
ORDER BY
due_date
, ord_num
DROP TABLE #TMP|||I assume you want to avoid a cursor...but, since the dattime vaalue is not unique, it still would be random|||That's what I was looking for.
Thanks|||I assume you want to avoid a cursor...but, since the dattime vaalue is not unique, it still would be random
Yeah, I'm actually rewriting an older sproc that uses a cursor. I'm trying to get away from them whenever I can.|||Interesting reading. Don't know if he ever sorted out his summary\ conclusion though - it bears little relation to information in the article. Anyhoo -
http://www.sql-server-performance.com/mm_cursor_friendly_problem.asp|||I'm thinking along the lines of an IDENTITY
SELECT T1.PRODUCT, T1.DUE_DATE, T1.ORD_NUM, T1.TONS,
'TTL_TONS'=( SELECT SUM(TONS) AS CUMM
FROM #TMP T2
WHERE T1.DUE_DATE > T2.DUE_DATE
-- AND T1.ORD_NUM > T2.ORD_NUM
AND T1.RowID > T2.RowId)
FROM #TMP T1|||Do you not feel a little dirty altering a table schema to meet the derived-data requirment of a query? More efficient but... well... naughty.|||I was actually on the verge of adding an identity column before posting this question. I really wanted to see if it could be done without one, because this method will make the code more understandable when I have to come back to it in 6 months.|||Do you not feel a little dirty altering a table schema to meet the derived-data requirment of a query? More efficient but... well... naughty.
Listen, if you want to use SQL to do ostuff that should be a presentation issue, then all bets are off.
Besides, I like being naughty|||Listen, if you want to use SQL to do ostuff that should be a presentation issue, then all bets are off.
...
Why do it at the presentaton level, when it's so much easier to do it in SQL?|||performance, performance, performance.|||pootle,
Not sure this is what you meant, but...
Yes, it's all about performance: I imagine it would take me a few weeks to rewrite the 3 reports that hit the recordset my sproc supplies. Once that was done, my guess is that it would take 5 minutes for the biggest report to generate "on demand". My users would throw a fit over a report taking that long. This sproc takes 6 seconds now, (it took 6 minutes when I was using a cursor), and the report comes up instantly.
So why not use the most efficient tool for the job?|||You don't think iot would be fatser on the fron end?
What reporting tool are you using?
Go Rangers!|||I'm using Actuate report writer. Since I can use a sproc to supply data to the report, and pass parameters back and forth between the two, I guess I've always viewed the sproc as just a part of the report.|||No experience of actuate. In access (where you know most of my experience lies :D) there is no real overhead for running totals. I am surprised you anticipate such a hit.
The performance thing is:
You have (probably) one database server.
You have n clients.
If you make the server perform presentation manipulations for every data request for these three reports then you are using up scarce resources on every call. Get the client to do this and you distribute the processing around your network. Even if the server does this more quickly it does not follow that the process is more efficient.
Case in point see below:
CREATE TABLE #TMP
(
DUE_DATE DATETIME,
ORD_NUM CHAR(10),
PRODUCT CHAR(3),
TONS REAL
)
INSERT INTO #TMP
SELECT'20070223','07026.0030','ABC', 3.375
UNION ALL
SELECT'20070223','07047.0059','ABC', 3.375
UNION ALL
SELECT'20070223','07053.0080','ABC', 3.375
UNION ALL
SELECT'20070224','07045.0030','ABC', 2.25
UNION ALL
SELECT'20070225','07045.0027','ABC',1.125
UNION ALL
SELECT'20070225','07046.0070','ABC',6.75
SET STATISTICS IO ON
SELECT T1.PRODUCT
, T1.DUE_DATE
, T1.ORD_NUM
, T1.TONS
,'TTL_TONS'=(SELECT SUM(TONS)AS CUMM
FROM #TMP T2
WHERE T1.DUE_DATE>=T2.DUE_DATE
AND T1.ORD_NUM >=CASE
WHEN T1.DUE_DATE=T2.DUE_DATE THEN
T2.ORD_NUM
ELSE
T1.ORD_NUM
END)
FROM #TMP T1
ORDER BY
due_date
, ord_num
SELECT T1.PRODUCT
, T1.DUE_DATE
, T1.ORD_NUM
, T1.TONS
FROM #TMP T1
ORDER BY
due_date
, ord_num
SET STATISTICS IO OFF
DROP TABLE #TMP
This results in (slightly edited but only for dsiplay puposes):
Table '#TMP'. Scan count 7, logical reads 7, physical reads 0, read-ahead reads 0.
Table '#TMP'. Scan count 1, logical reads 1, physical reads 0, read-ahead reads 0.
Seven fold increase in logical reads if working out the total in the BE.|||might latest readings have been telling me running totals are a legitimate use of cursors with regards to performance.|||This is something of a series of related blog posts on running totals. First one shows why a cursor is faster than one type of set-based method. The middle link has a faster method which is set based. the last method is a bit faster still but requires a CLR proc.
http://www.sqljunkies.com/WebLog/amachanic/archive/2006/02/28/18286.aspx
http://blogs.conchango.com/jamiethomson/archive/2006/02/28/3001.aspx
http://www.sqljunkies.com/WebLog/amachanic/archive/2006/02/28/18309.aspx
EDIT: i think it's generally true that if you find yourself writing a cursor and don't see another way, the CLR will be much faster if you can use it. requires 2005 obviously.|||Post six in this thread. Come on chaps - keep up :p|||Thanks to all for the help. After reading the posts (and links), I'm afraid I probably did this the wrong way - but hey, it's a lot faster and more accurate than it used to be :)
What I was looking for here was just a small piece of what I was trying to do,
and these totals were necessary for processing further down in the sproc.
Thanks again
Oh, and Pootle...
My knowledge of servers is limited to: They are a magic box located in a different building, that cause the 50 year old men
that work on them to grow pony-tails.
Wednesday, March 7, 2012
Cube Wizard not detecting a Fact Table in SSAS
Hi,
While trying to create a Cube using the Cube Wizard, Under 'Identify Fact and Dimension Tables' screen, When I try to check either 'Fact' or 'Dimension' option box for a FactTable, SS is flagging an error.
Can someone tell me as to why this is happening ?
The wizard relies on the relationships in the DSV, so if these are missing or incorrect the wizard may have problems figuring things out.|||A little more specificially, every Fact Table must have one or more Dimension Tables which can be reached from it based on the relationships in the DSV. You probably just need to select a table for use as a dimension, possibly even the fact table itself, and then the wizard should let you continue.|||Thanks Darren and Matt for your replies.
I modified the Fact table to have FKs with Dimension Tables and now the Wizard detects it successfully.
Cheers,
Sundar
Cube Wizard not detecting a Fact Table in SSAS
Hi,
While trying to create a Cube using the Cube Wizard, Under 'Identify Fact and Dimension Tables' screen, When I try to check either 'Fact' or 'Dimension' option box for a FactTable, SS is flagging an error.
Can someone tell me as to why this is happening ?
The wizard relies on the relationships in the DSV, so if these are missing or incorrect the wizard may have problems figuring things out.|||A little more specificially, every Fact Table must have one or more Dimension Tables which can be reached from it based on the relationships in the DSV. You probably just need to select a table for use as a dimension, possibly even the fact table itself, and then the wizard should let you continue.|||Thanks Darren and Matt for your replies.
I modified the Fact table to have FKs with Dimension Tables and now the Wizard detects it successfully.
Cheers,
Sundar
Cube Wizard not detecting a Fact Table in SSAS
Hi,
While trying to create a Cube using the Cube Wizard, Under 'Identify Fact and Dimension Tables' screen, When I try to check either 'Fact' or 'Dimension' option box for a FactTable, SS is flagging an error.
Can someone tell me as to why this is happening ?
The wizard relies on the relationships in the DSV, so if these are missing or incorrect the wizard may have problems figuring things out.|||A little more specificially, every Fact Table must have one or more Dimension Tables which can be reached from it based on the relationships in the DSV. You probably just need to select a table for use as a dimension, possibly even the fact table itself, and then the wizard should let you continue.|||Thanks Darren and Matt for your replies.
I modified the Fact table to have FKs with Dimension Tables and now the Wizard detects it successfully.
Cheers,
Sundar
Cube Wizard not detecting a Fact Table in SSAS
Hi,
While trying to create a Cube using the Cube Wizard, Under 'Identify Fact and Dimension Tables' screen, When I try to check either 'Fact' or 'Dimension' option box for a FactTable, SS is flagging an error.
Can someone tell me as to why this is happening ?
The wizard relies on the relationships in the DSV, so if these are missing or incorrect the wizard may have problems figuring things out.|||A little more specificially, every Fact Table must have one or more Dimension Tables which can be reached from it based on the relationships in the DSV. You probably just need to select a table for use as a dimension, possibly even the fact table itself, and then the wizard should let you continue.|||Thanks Darren and Matt for your replies.
I modified the Fact table to have FKs with Dimension Tables and now the Wizard detects it successfully.
Cheers,
Sundar
Cube showing slightly different data than in data source...?
I am very perplexed with this problem I'm having. I work for a website-based
company and my job is to create a data warehouse based on usage of the site.
We have a Central Logging Database that logs every single hit to the site,
then i have a stored procedure that picks up these hits, does a bit of data
scrubbing and transformation, and puts them into a Warehouse database. i
then have an Analysis Services cube that points at this warehouse database.
I then use Reporting Services and MDX to create reports based on this usage
info.
Scenario: the total hits in the database can be further grouped into
companies, so reports can be run to show a company's usage of the site.
Companies are then further divided into Users belonging to a company. I.e.
reports are generally run to show a company's usage, broken down into
individual users within that company.
In order to check that my warehouse-load stored procedure works properly I
compared the amount of hits in the Central Logging Database (where all hits
are originally recorded) with hits in the final Warehouse database to see if
they balance. Everything looks fine and hunky-dory.
My problem is this: When I browse the cube in analysis manager, some of the
companies have a higher hit count, i.e. show more hits, than actually exist
in any of the original databases! In the cube one company is even showing
1,000 hits for a user who does not have ANY hits in any of the original
databases!!!
the total amount of hits shown in the cube is equal to the original
databases, so some how it balances. but i don't understand where all this
extra\incorrect data is coming from.
My cube consists of a very simple Star-schema design. one main table called
Hits, and UserAccount, BusinessEntity, and Date dimensions. the Hits table
consists of the following columns:
Hit_ID (int)
DatabaseSource (int)
UserAccountID (int)
BusinessEntityID (int)
LogDateID (int)
One hit is defined by a Hit_ID and DatabaseSource (these two form a
composite primary key).
My Measure in the cube is the Hit_ID.
Does anyone know what i could possibly be doing wrong? I would be very
grateful for any bit of help anyone could provide.
Thanks in advance!
I am making a basic assumption here about the measure Hit_ID which is also
part of your key --> that you are COUNTING hits.
Try Count Distinct within Analysis Services instead of teh default Count. If
that does not work, I suggest introducing a measure within your fact table
called count_hits or something which will have a value of 1 (one) for every
unique combination of your keys. Then use this with the Sum aggregate
function to define your measure within the cube.
Let us know if it worked.
Thanks and hope this helps.
Rangarajan Suresh
www.picarossolutions.com
"Neile" wrote:
> Hello,
> I am very perplexed with this problem I'm having. I work for a website-based
> company and my job is to create a data warehouse based on usage of the site.
> We have a Central Logging Database that logs every single hit to the site,
> then i have a stored procedure that picks up these hits, does a bit of data
> scrubbing and transformation, and puts them into a Warehouse database. i
> then have an Analysis Services cube that points at this warehouse database.
> I then use Reporting Services and MDX to create reports based on this usage
> info.
> Scenario: the total hits in the database can be further grouped into
> companies, so reports can be run to show a company's usage of the site.
> Companies are then further divided into Users belonging to a company. I.e.
> reports are generally run to show a company's usage, broken down into
> individual users within that company.
> In order to check that my warehouse-load stored procedure works properly I
> compared the amount of hits in the Central Logging Database (where all hits
> are originally recorded) with hits in the final Warehouse database to see if
> they balance. Everything looks fine and hunky-dory.
> My problem is this: When I browse the cube in analysis manager, some of the
> companies have a higher hit count, i.e. show more hits, than actually exist
> in any of the original databases! In the cube one company is even showing
> 1,000 hits for a user who does not have ANY hits in any of the original
> databases!!!
> the total amount of hits shown in the cube is equal to the original
> databases, so some how it balances. but i don't understand where all this
> extra\incorrect data is coming from.
> My cube consists of a very simple Star-schema design. one main table called
> Hits, and UserAccount, BusinessEntity, and Date dimensions. the Hits table
> consists of the following columns:
> Hit_ID (int)
> DatabaseSource (int)
> UserAccountID (int)
> BusinessEntityID (int)
> LogDateID (int)
> One hit is defined by a Hit_ID and DatabaseSource (these two form a
> composite primary key).
> My Measure in the cube is the Hit_ID.
> Does anyone know what i could possibly be doing wrong? I would be very
> grateful for any bit of help anyone could provide.
> Thanks in advance!
Cube showing slightly different data than in data source...?
I am very perplexed with this problem I'm having. I work for a website-based
company and my job is to create a data warehouse based on usage of the site.
We have a Central Logging Database that logs every single hit to the site,
then i have a stored procedure that picks up these hits, does a bit of data
scrubbing and transformation, and puts them into a Warehouse database. i
then have an Analysis Services cube that points at this warehouse database.
I then use Reporting Services and MDX to create reports based on this usage
info.
Scenario: the total hits in the database can be further grouped into
companies, so reports can be run to show a company's usage of the site.
Companies are then further divided into Users belonging to a company. I.e.
reports are generally run to show a company's usage, broken down into
individual users within that company.
In order to check that my warehouse-load stored procedure works properly I
compared the amount of hits in the Central Logging Database (where all hits
are originally recorded) with hits in the final Warehouse database to see if
they balance. Everything looks fine and hunky-dory.
My problem is this: When I browse the cube in analysis manager, some of the
companies have a higher hit count, i.e. show more hits, than actually exist
in any of the original databases! In the cube one company is even showing
1,000 hits for a user who does not have ANY hits in any of the original
databases!!!
the total amount of hits shown in the cube is equal to the original
databases, so some how it balances. but i don't understand where all this
extra\incorrect data is coming from.
My cube consists of a very simple Star-schema design. one main table called
Hits, and UserAccount, BusinessEntity, and Date dimensions. the Hits table
consists of the following columns:
Hit_ID (int)
DatabaseSource (int)
UserAccountID (int)
BusinessEntityID (int)
LogDateID (int)
One hit is defined by a Hit_ID and DatabaseSource (these two form a
composite primary key).
My Measure in the cube is the Hit_ID.
Does anyone know what i could possibly be doing wrong? I would be very
grateful for any bit of help anyone could provide.
Thanks in advance!
I presume your measure is a Count of HitID to have the number of hit by
users...
How many rows are loaded when you process the cube? (normally this number =
number rows in the database)
There is any join between the Hit table and the others? (joins created by AS
to load the cube; see the query executed by AS)
does the user appear twice in the database?
if your users are under the company and if 1 user can appear in more then 1
company, then you can count twice (or more) the same hit.
"Neile" <Neile@.discussions.microsoft.com> a crit dans le message de news:
E05E7B92-22C7-4811-9DDF-B1C9C25EEBD0@.microsoft.com...
> Hello,
> I am very perplexed with this problem I'm having. I work for a
> website-based
> company and my job is to create a data warehouse based on usage of the
> site.
> We have a Central Logging Database that logs every single hit to the site,
> then i have a stored procedure that picks up these hits, does a bit of
> data
> scrubbing and transformation, and puts them into a Warehouse database. i
> then have an Analysis Services cube that points at this warehouse
> database.
> I then use Reporting Services and MDX to create reports based on this
> usage
> info.
> Scenario: the total hits in the database can be further grouped into
> companies, so reports can be run to show a company's usage of the site.
> Companies are then further divided into Users belonging to a company. I.e.
> reports are generally run to show a company's usage, broken down into
> individual users within that company.
> In order to check that my warehouse-load stored procedure works properly I
> compared the amount of hits in the Central Logging Database (where all
> hits
> are originally recorded) with hits in the final Warehouse database to see
> if
> they balance. Everything looks fine and hunky-dory.
> My problem is this: When I browse the cube in analysis manager, some of
> the
> companies have a higher hit count, i.e. show more hits, than actually
> exist
> in any of the original databases! In the cube one company is even showing
> 1,000 hits for a user who does not have ANY hits in any of the original
> databases!!!
> the total amount of hits shown in the cube is equal to the original
> databases, so some how it balances. but i don't understand where all this
> extra\incorrect data is coming from.
> My cube consists of a very simple Star-schema design. one main table
> called
> Hits, and UserAccount, BusinessEntity, and Date dimensions. the Hits table
> consists of the following columns:
> Hit_ID (int)
> DatabaseSource (int)
> UserAccountID (int)
> BusinessEntityID (int)
> LogDateID (int)
> One hit is defined by a Hit_ID and DatabaseSource (these two form a
> composite primary key).
> My Measure in the cube is the Hit_ID.
> Does anyone know what i could possibly be doing wrong? I would be very
> grateful for any bit of help anyone could provide.
> Thanks in advance!
>
Saturday, February 25, 2012
Cube installation without VS
I created a cube and I want to give it to several persons for the installation on their SQL Server 2005. Is it possible to create something like an installation package (similar to the deployment manifest in SSIS)?
Thanks for any help!
No, but you can script out the database as an XMLA script and then execute it on another server. To create the script, use SQL Management Studio and right-click on the Analysis Services object. One of the options should be Script \ Create.
There are several ways to execute the XMLA script on the remote server. One way would be to enter it as a SQL Agent Job. One of the command types is Analysis Services DDL script. Another way would be to exeute it via an SSIS package. In fact you could put the XMLA script right in the SSIS package and then deploy the package.
One of the features which unfortunately was a command-line utility to execute a XMLA script. We are trying to get it released in one of the web release of the Samples.msi later next year.
Hope that helps.
_-_-_ Dave|||That's exactly what I need. Thanks alot!
Friday, February 24, 2012
Cube DDL reverse engineer ?
Hi guys
I have built several cubes. However I would need to create local cubes from the built cubes in Analysis Services. As a result I need to work out the DDL for my existing cubes. However the cube contains many mdx calculated members. I was wondering if it would be easier to simply generate the DDL from my existing cube in Analysis Services.
Does anyone know any third party tools that I can use to reverse engineer the DDL from the built cubes in Analysis Services ?
Thanks
Tom
Why not just load it in Server Manager and tell it to Script Database as Create. That should give you the full DDL I believe.|||I want to script the cube not the sql server database.If there is a way could you please give a more detailed description of the process.
I really appreciate it ! thankyou !
Tom|||The cube is contained in an Analysis Services database, not a SQL Server database. Or are you saying that your AS database contains multiple cubes and you only want to script out one?
Start SQL Server Management Studio
When asked to connect to server drop the Server type down and pick Analysis Services
Expand the databases node.
Right click on a database
Select Script Database as Create To
Alternatively if you want just one cube expadn the cubes node
Right click on the cube you are interested in
Select Script Cube as Create To|||Start SQL Server Management Studio
When asked to connect to server drop the Server type down and pick Analysis Services
Expand the databases node.
Right click on a database
Select Script Database as Create To
__
I've started sql server enterprise manager. When I tried to make a new registration under a sql server group it DOES NOT pick up analysis services. I know they're running on different ports why would sql server manager pickup analysis services ?
can you confirm the process please. I really can't see it working. As there's no possible way for sql server manager to connect to analysis services.
Thankyou
Tom
|||Tom,
I think I see the problem. I'm betting you are using Analysis Services 2000, not Analysis Services 2005...
With SQL Server 2005, the new management tool (called SQL Server Management Studio) replaces Enteprise Manager in SQL Server 2000. SQL Server Management Studio does indeed have the ability to connect to Analysis Services as well as SQL Server. And it has the ability to script the DDL for an entire Analysis Services 2005 database as well as any portion thereof.
However, since you are likely using Analysis Services 2000, this won't work for you. If you need to generate the DDL to create a cube, you'll have to look to some third-party tool options for this as Analysis Manager does not have the ability to generate DDL. Take a look at the short list of options mentioned on Mosha's website at http://www.mosha.com/msolap/util.htm#Metadata. This should at least give you some ideas and options...
Dave Fackler
|||thanks for that at least now I have a good idea what the other person's talking about
Thanks
Tom
cube cretion & report accessing it
Hi,
I’m new with SSAS but I had know how to create a cube and I could able to connect to SSAS database and view the cube I had created. But I do not understand if some Reporting tool wanted to access the data from cube, will it connect cube and do the manipulation as per the report requirement or I have to do create a cube specific to the each report.
Another clarification if I create a cube on show flick schema will that be any problem in accessing the data.
This are the very basic questions but I need to get more clarity
Thank you
Regarding cubes & reports, you should be able to create a single cube and use it across your reports. Each report would have one or more MDX queries associated with it to provide the data for the report. Depending on the tool you use, the MDX may or may not be easily accessible as the interface may provide a means of assembling the query without exposing the MDX to you.
Regarding the other, I'm not sure what "show flick shema" is.
Thanks,
Bryan