Thursday, March 29, 2012
Help with Cursor to insert 100 rows at a time
Can one of you help me with using a cursor that would insert only 100 rows at a time from source table 1 to target table 2. I am not able to loop beyond the first 100 rows.
Here is what I have till now:
CREATE procedure Insert100RowsAtaTime
AS
SET NOCOUNT ON
declare @.Col1 int
declare @.Col2 char(9)
DECLARE @.RETURNVALUE int
DECLARE @.ERRORMESSAGETXT varchar(510)
DECLARE @.ERRORNUM int
DECLARE @.LOCALROWCOUNT int
declare Insert_Cur cursor local fast_forward
FOR
SELECT top 100 Col1,Col2 from Table1
WHERE Col1 not in ( SELECT Col1 /* Col1 is PK. This statement is used to prevent the same rows from being inserted in Table 2*/
from Table2)
set @.RETURNVALUE = 0
set @.ERRORNUM = 0
BEGIN
open Insert_Cur
fetch NEXT from Insert_Cur into @.Col1, @.Col2
while (@.@.FETCH_STATUS = 0)
insert into Table2 (Col1,Col2) select @.Col1,@.Col2
SELECT @.ERRORNUM = @.@.ERROR, @.LOCALROWCOUNT = @.@.ROWCOUNT
IF @.ERRORNUM = 0
BEGIN
IF @.LOCALROWCOUNT >= 1
BEGIN
SELECT @.RETURNVALUE = 0
END
ELSE
BEGIN
SELECT @.RETURNVALUE = 1
RAISERROR ('INSERT FAILS',16, 1)
END
END
ELSE
BEGIN
SELECT @.ERRORMESSAGETXT = description FROM [master].[dbo].[sysmessages]
WHERE error = @.@.ERROR
RAISERROR (@.ERRORMESSAGETXT, 16, 1)
SELECT @.RETURNVALUE = 1
END
fetch NEXT from Insert_Cur into @.Col1, @.Col2
end
close Insert_Cur
deallocate Insert_Cur
RETURN @.RETURNVALUE
ENDFirst of all, I don't understand what you really want to do so I can't give you a usable or correct response. I can tell you almost certainly that a cursor is not the correct answer.
You have a PK. A cursor isn't needed and it will probably hurt you in terms of both complexity and performance.
Can you describe what you really want in terms of the real world? In business or end-user terms, not in geek speak.
There are definitely ways to do what you want. They are probably simple and fast. I don't know enough to help you yet, but if you describe what you are trying to do a bit better then I'd bet that someone here can help.
-PatP|||It seems to me your not inserting all rows with 100 rows at the time, you're inserting 100 rows one at the time. After row no 100, the cursor is finished and your procedure is done.
This should be more like what you descibe (albeit not the most efficient way, but at least it eliminates the cursor):
WHILE EXISTS (
SELECT 1
FROM Table1
WHERE Col1 NOT IN (SELECT Col1 FROM Table2)
)
BEGIN
INSERT table2 (Col1, Col2)
SELECT top 100 Col1,Col2
FROM Table1
WHERE Col1 NOT IN (SELECT Col1 FROM Table2)
-- Maybe do some error checking here
END
A question about your code:
SELECT @.ERRORMESSAGETXT = description FROM [master].[dbo].[sysmessages]
WHERE error = @.@.ERROR
RAISERROR (@.ERRORMESSAGETXT, 16, 1)
What's this supposed to do?
1) The message is already raised the moment the error occurs
2) What about the placeholders in the messages?
3) @.@.ERROR at that moment is always 0|||Table 1 has over 500 million rows. The task is To select data from Table 1 (based on business rules) and insert into Table 2. The concern was Selecting all data may take a long time to execute and in case of any issue with the quety, a long time to roll back. Hence 100 rows at a time using a cursor.|||As mentioned, forget the cursor! They are for row-by-row processing.
Help with cursor and decimal values
s
are below 1. I am trying to use this to apply a factor and always get a zero
if the factor below 1, as a result my logic fails.
Can some one help me on this?
-- ========== Table & data =============
CREATE Table TestFactor (TestFactorId int, FactorValue decimal(5,2))
INSERT INTO TestFactor VALUES (1, 0.25)
INSERT INTO TestFactor VALUES (2, 0.50)
INSERT INTO TestFactor VALUES (3, 0.75)
INSERT INTO TestFactor VALUES (4, 0.125)
INSERT INTO TestFactor VALUES (5, 0.25)
INSERT INTO TestFactor VALUES (6, 2)
INSERT INTO TestFactor VALUES (7, 1)
-- ========== Table & data =============
DECLARE @.Factor decimal
DECLARE my CURSOR
FOR SELECT FactorValue from TestFactor
OPEN my
FETCH NEXT FROM my INTO
@.Factor
SELECT @.Factor
WHILE @.@.FETCH_STATUS = 0
BEGIN
FETCH NEXT FROM my INTO
@.Factor
SELECT @.Factor
END
CLOSE my
DEALLOCATE my
Thankschange DECLARE @.Factor decimal to
DECLARE @.Factor decimal (5,2) -- same as in the table
http://sqlservercode.blogspot.com/|||Change
DECLARE @.Factor decimal
to
DECLARE @.Factor decimal(5,2)
"Ram" wrote:
> The following table when using a cursor gives 0 for decimals where the val
ues
> are below 1. I am trying to use this to apply a factor and always get a ze
ro
> if the factor below 1, as a result my logic fails.
> Can some one help me on this?
> -- ========== Table & data =============
> CREATE Table TestFactor (TestFactorId int, FactorValue decimal(5,2))
> INSERT INTO TestFactor VALUES (1, 0.25)
> INSERT INTO TestFactor VALUES (2, 0.50)
> INSERT INTO TestFactor VALUES (3, 0.75)
> INSERT INTO TestFactor VALUES (4, 0.125)
> INSERT INTO TestFactor VALUES (5, 0.25)
> INSERT INTO TestFactor VALUES (6, 2)
> INSERT INTO TestFactor VALUES (7, 1)
> -- ========== Table & data =============
>
> DECLARE @.Factor decimal
> DECLARE my CURSOR
> FOR SELECT FactorValue from TestFactor
> OPEN my
> FETCH NEXT FROM my INTO
> @.Factor
> SELECT @.Factor
> WHILE @.@.FETCH_STATUS = 0
> BEGIN
> FETCH NEXT FROM my INTO
> @.Factor
> SELECT @.Factor
> END
> CLOSE my
> DEALLOCATE my
> Thanks
>|||Thanks Mark & SQL
I was going crazy on this. I think I need a vacation
"Mark Williams" wrote:
> Change
> DECLARE @.Factor decimal
> to
> DECLARE @.Factor decimal(5,2)
> "Ram" wrote:
>
Help with CURSOR
For example i have the tree
Section 1
|-Section 1.1
Section 2
|-Section 2.1
The "Section" table contains 3 fields: id, parent_id, and caption. ID is the identity of the section record and parent_id contains NULL or the ID of this record's parent to create a child. So "Section 1" (id=1, parent_id=null), "Section 2" (id=2, parent_id=null), "Section 1.1" (id=3, parent_id=1), "Section 2.1" (id=4,parent_id=2).
I would like to copy this sucture to create 4 new sections but they need to maintain their id/parent_id relationships BUT with new IDs. For this i created the following stored procedure:
-
CREATE PROCEDURE [dbo].[CopySection]
AS
-- Declare a temporary variable table for storing the sections
DECLARE @.tblSection TABLE
(
id int,
parent_id int,
caption varchar(max),
)
DECLARE @.newAgendaID int, @.newSectionID int;
DECLARE @.tid int, @.tparent_id int, @.tcaption varchar(max);
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Copy the desired sections into the local temp variable table
INSERT INTO @.tblSection SELECT id, parent_id, caption FROM tblSection ORDER BY parent_id;
-- Using a cursor, step through all temp sections and add them to the tblSection but note its new ID
DECLARE c1 CURSOR FOR SELECT * FROM @.tblSection ORDER BY parent_id FOR UPDATE OF parent_id;
OPEN c1;
FETCH NEXT FROM c1 INTO @.tid, @.tparent_id, @.tcaption;
WHILE @.@.FETCH_STATUS = 0
BEGIN
-- Insert the new Section and record the identity
INSERT INTO tblSection (agenda_id, parent_id, caption) VALUES (@.tparent_id, @.tcaption);
SET @.newSectionID = SCOPE_IDENTITY();
-- Update the temp variable table with the new identity from the newly created real section in tblSection
-- Update all temp variable records to point to the new parent_id
UPDATE @.tblSection SET parent_id = @.newSectionID WHERE parent_id = @.tid;
FETCH NEXT FROM c1 INTO @.tid, @.tparent_id, @.tcaption;
END
CLOSE c1
DEALLOCATE c1
END
-
The critical "UPDATE @.tblSection" part doesnt seem to update the temp variable table with the @.newSectionID (the actual section identity obtained after inserting a real record into the tblSection table). So in the end the inserted records into tblSection still point to the incorrect parent_id instead of the copied record's parent_id.
Maybe I'm using CURSOR incorrectly or not setting a parameter so that it refreshes its recordset?
You can use the following query.. Here we are not using any cursor..
Declare @.Section Table
(
ParentId int,
Caption varchar(100)
)
Declare @.ParentId as int;
Declare @.NewParentId as int;
Declare @.Caption as varchar(100);
Insert into @.Section
Select Id,Caption from tblSection Where Parent_ID is NULL -- you can filter your desired id
While Exists(Select 1 From @.Section)
Begin
Select Top 1 @.ParentId = ParentId, @.Caption = Caption From @.Section;
Insert Into tblSection(parent_id, caption) values(null, @.Caption);
Select @.NewParentId =Scope_Identity();
Delete From @.Section Where ParentId = @.ParentId ;
Insert Into tblSection(parent_id, caption)
Select @.NewParentId, caption From tblSection Where parent_id = @.ParentId;
End
Select * From tblSection;
|||I have tried quantass 's code and it does not do the parentid properly as it keeps using the old parentid of the previous tree structure - can you please show me the actual code you got it working or how can it be solved please?
I really am in desperate need of getting one that actually works properly.
Thanks
|||Which version of SQL server are you running?|||I am using SQL server 2005 - I think I have tried to get it working but I don't know if this is the correct approach which I have modified quanass's sql.
-- Declare a temporary variable table for storing the sections
DECLARE @.tblSection TABLE
(
id int,
parent_id int,
caption varchar(max),
old_id int
)
DECLARE @.newSectionID int;
DECLARE @.tid int, @.tparent_id int, @.tcaption varchar(max),@.told_id int;
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Copy the desired sections into the local temp variable table
INSERT INTO @.tblSection SELECT id, parent_id, caption, old_id FROM tblSection ORDER BY parent_id;
-- Using a cursor, step through all temp sections and add them to the tblSection but note its new ID
DECLARE c1 CURSOR FOR SELECT * FROM @.tblSection ORDER BY parent_id FOR UPDATE OF parent_id;
OPEN c1;
FETCH NEXT FROM c1 INTO @.tid, @.tparent_id, @.tcaption,@.told_id;
WHILE @.@.FETCH_STATUS = 0
BEGIN
-- Insert the new Section and record the identity
INSERT INTO tblSection (parent_id, caption) VALUES (@.tparent_id, @.tcaption);
SET @.newSectionID = SCOPE_IDENTITY();
-- Update the temp variable table with the new identity from the newly created real section in tblSection
-- Update all temp variable records to point to the new parent_id
UPDATE @.tblSection SET parent_id = @.newSectionID, old_id = @.tid WHERE parent_id = @.tid;
FETCH NEXT FROM c1 INTO @.tid, @.tparent_id, @.tcaption,@.told_id;
END
CLOSE c1
DEALLOCATE c1
SELECT * FROM @.tblSection <from this point I tried to get the parentid done properly and not hanging onto the old parentID
WHILE EXISTS(SELECT 1 FROM @.tblSection)
BEGIN
SELECT @.tparent_id=parent_id,@.told_id=old_id FROM @.tblSection
UPDATE tblSection SET[parent_id] = @.tparent_id WHERE parent_id = @.told_id
DELETE FROM @.tblSection WHERE UpLevelID = @.tUpLevelID
END
END
I could do with some feedback and whether it can be improved and what can be changed on this?
Thanks
|||I have tried with the modified SQL as above and it did work with small data. But I found if I tried with 100 records - the parentid gets really messed up and doesn't look right.
I would really appreciate any help and examples or show me the corrections on my modified SQL please as I have spent a week struggling in vain to actually get it working properly.
ID ParentID MenuID Name
====================
1 0 1 sun
2 1 1 mars
3 2 1 charon
4 2 1 flubbie
5 3 1 blub
6 0 2 sun <-new menu as menuID of 1as it is a copy of it
7 6 2 mars
8 7 2 charon
9 7 2 flubbie
10 8 2 blub
Please help as I am in desperate situation on this. Thanks
|||I will give it a look and see what I can come up with; sorry I didn't respond yesterday. I've been off in DB2 land most of this week.|||This is my first pass and I feel like I didn't do a good job with it. It sure looks WAY more long-winded than your version. Also, I don't care for the WHILE loop in my stored procedure, but I have to somehow retrieve the IDENTITY values; nonetheless, it at least seems to to work. First, I defined this table for the mock-up:
create table dbo.jHierMenu
( ID integer identity (21, 1)
constraint pk_jHierMenu primary key,
ParentID integer null,
MenuID integer null,
[Name] varchar(20) not null
)
gocreate index jHierMenu_Menu_ndx
on dbo.jHierMenu (MenuID, ParentID, ID, [Name])
goinsert into dbo.jHierMenu values (0, 1, 'sun')
insert into dbo.jHierMenu values (21, 1, 'mars')
insert into dbo.jHierMenu values (22, 1, 'charon')
insert into dbo.jHierMenu values (22, 1, 'flubbie')
insert into dbo.jHierMenu values (23, 1, 'blub')
select * from dbo.jHierMenu
I then created a function that I could use as a building block:
create function dbo.relativeMenuHierarchy
( @.pm_MenuID integer
)
returns @.menuHierarchy table
( rid integer identity primary key,
ParentRid integer null,
ID integer not null,
ParentID integer null,
MenuID integer not null,
[Name] varchar (20) null,
hierLevel integer not null,
unique (hierLevel, rid)
)
as
beginif ( select count(*) from dbo.jHierMenu
where menuId = @.pm_menuID
) < 1
return;;with menuHierCTE
as
(
select id,
ParentID,
MenuID,
[Name],
0 as hierLevel
from dbo.jHierMenu
where MenuID = @.pm_menuID
and ParentID = 0
union all
select a.ID,
a.ParentID,
a.MenuID,
a.[Name],
cte.hierLevel + 1
from menuHierCTE as cte
inner join dbo.jHierMenu a
on a.menuId = @.pm_menuID
and a.parentID = cte.id
)
insert into @.menuHierarchy
select case when parentId = 0 then 0 else null end,
id,
parentId,
menuId,
[Name],
hierLevel
from menuHierCTEdeclare @.secondHierarchy table
( rid integer primary key,
ParentRid integer null,
ID integer not null,
ParentID integer null,
MenuID integer not null,
[Name] varchar (20) null,
hierLevel integer not null,
unique (hierLevel, rid)
)insert into @.secondHierarchy
select * from @.menuHierarchyupdate @.menuHierarchy
set ParentRid = a.rid
from @.secondHierarchy a
inner join @.menuHierarchy b
on a.hierLevel = b.hierLevel - 1
and a.id = b.parentId
inner join small_iterator (nolock) i
on iter = b.hierLevel
and iter <= ( select max(hierLevel)
from @.secondHierarchy
)return
end
go
select rid,
parentRid,
id,
parentId,
menuId,
[name],
hierLevel
from relativeMenuHierarchy (1);-- rid parentRid id parentId menuId name hierLevel
-- -- -- --
-- 1 0 21 0 1 sun 0
-- 2 1 22 21 1 mars 1
-- 3 2 23 22 1 charon 2
-- 4 2 24 22 1 flubbie 2
-- 5 3 25 23 1 blub 3
Once I had the function working, I assembled a stored procedure to perform the actual work:
create procedure dbo.replicateMenu
( @.pm_oldMenuId integer,
@.pm_newMenuId integer
)
asif exists
( select 0 from jHierMenu
where menuId = @.pm_newMenuId
)
begin
raiserror ('Menu ID ''%d'' is NOT a new menu id!', 0, 1, @.pm_newMenuID)
return 21001
enddeclare @.menuHierarchy table
( rid integer primary key,
ParentRid integer null,
ID integer null,
ParentID integer null,
MenuID integer not null,
[Name] varchar (20) null,
hierLevel integer not null,
unique (hierLevel, rid)
)insert into @.menuHierarchy
select rid,
parentRid,
null as ID,
null as ParentId,
menuId,
[name],
hierLevel
from dbo.relativeMenuHierarchy (@.pm_oldMenuID)declare @.nextRid integer
declare @.lastId integer
declare @.maxRid integerset @.maxRid = ( select max(rid) from @.menuHierarchy )
if @.maxRid = 0
return 0insert into dbo.jHierMenu
select 0 as parentId,
@.pm_newMenuId as [MenuId],
[Name]
from @.menuHierarchy
where rid = 1
set @.lastId = scope_identity()update @.menuHierarchy
set id = @.lastId,
parentId = 0
where rid = 1set @.nextRid = 1
while @.nextRid < @.maxRid
beginset @.nextRid = @.nextRid + 1
insert into dbo.jHierMenu
select p.id as ParentId,
@.pm_newMenuId as [MenuId],
a.[name]
from @.menuHierarchy a
inner join @.menuHierarchy p
on a.parentRid = p.rid
where a.rid = @.nextRidset @.lastId = scope_identity()
update @.menuHierarchy
set id = @.lastId,
parentId = h.parentId
from @.menuHierarchy a
inner join dbo.jHierMenu h
on h.id = @.lastId
and a.rid = @.nextRidend
return 0
go
exec replicateMenu 1, 101
select * from jHierMenu
-- ID ParentID MenuID Name
-- -- -- --
-- 21 0 1 sun
-- 22 21 1 mars
-- 23 22 1 charon
-- 24 22 1 flubbie
-- 25 23 1 blub-- 65 0 101 sun
-- 66 65 101 mars
-- 67 66 101 charon
-- 68 66 101 flubbie
-- 69 67 101 blubdelete from jHierMenu where menuId = 101
I will try this out with a 100 and 200 row test. I'm kinda fried right now and I must step back for at least a little while.
I tried the stored procedure with a 100-row menu and I feel better about all of this -- especially the function. I was able to use the function compare the two menus and verify that the replication had worked correctly. This also means that it would be relatively easy to create a "compareMenu" stored procedure or function. I started by truncating the mock-up table and inserting 100 random rows:
truncate table dbo.jHierMenu
goset identity_insert tempdb.dbo.jHierMenu ON
insert into dbo.jHierMenu
( id,
parentId,
menuId,
name
)
select 1 as id,
0 as parentId,
1 as menuId,
'Name 1' as [Name]insert into dbo.jHierMenu
( id,
parentId,
menuId,
name
)
select iter as id,
floor(1 + (cast (iter as float) - 1.99999) * dbo.randValue(iter))
as parentId,
1 as menuId,
'Name ' + convert (varchar (5), iter) as [Name]
from small_iterator
where iter > 1
and iter <= 100
goset identity_insert tempdb.dbo.jHierMenu Off
go
select * from dbo.jHierMenu order by id
-- ID ParentID MenuID Name
-- -- --
-- 1 0 1 Name 1
-- 2 1 1 Name 2
-- 3 1 1 Name 3
-- 4 1 1 Name 4
-- 5 3 1 Name 5
-- 6 4 1 Name 6
-- 7 5 1 Name 7
-- ...
-- 99 84 1 Name 99
-- 100 12 1 Name 100
I then ran the "replicateMenu" stored procedure and then ran the query that follows to verify that the new menu was identical in structure to the old menu:
|||set nocount on
--delete from dbo.jHierMenu where menuId = 101
exec replicateMenu 1, 101-- -
-- Uncomment the AND statement if you want to display
-- only the exceptions.
-- -
select a.rid,
a.[name],
b.rid,
b.[name]
from relativeMenuHierarchy (1) a
inner join relativeMenuHierarchy (101) b
on a.rid = b.rid
-- and a.name <> b.name-- rid name rid name
-- - -
-- 1 Name 1 1 Name 1
-- 2 Name 2 2 Name 2
-- 3 Name 3 3 Name 3
-- ...
-- 99 Name 84 99 Name 84
-- 100 Name 99 100 Name 99
Hi
I had read through your examples and it seems much cleaner and efficient than mine (a compliment). I have tested out my stored procedure several times and it does work (at least I think it does). However I am going try yours as well and test it out again.
I also realise supposing someone comes a long and deletes an item and the rest of items becomes obselete if you like as the first item is missing so the uplevel gets skewed up. So if they copy that menu with the missing item and the rest of the items with obselete uplevel, theoretically, the copied menu would have the rest of the items with the old obselete uplevelID - would that break the stored procedure coding or mess the structure when copying a menu? I noticed it does happen with my old stored proc - could that easily be remedied?
I really appreciate the time and effort you have put in this stored procedure and my gratitude of thanks goes towards you. I found what you have done with the stored procedure and testing has been a big lesson for me and hopefully I will improve my 'thinking out of the box'.
Thanks again, will keep you posted to let you know how I get on with the testing on this.
Help with CURSOR
For example i have the tree
Section 1
|-Section 1.1
Section 2
|-Section 2.1
The "Section" table contains 3 fields: id, parent_id, and caption. ID is the identity of the section record and parent_id contains NULL or the ID of this record's parent to create a child. So "Section 1" (id=1, parent_id=null), "Section 2" (id=2, parent_id=null), "Section 1.1" (id=3, parent_id=1), "Section 2.1" (id=4,parent_id=2).
I would like to copy this sucture to create 4 new sections but they need to maintain their id/parent_id relationships BUT with new IDs. For this i created the following stored procedure:
-
CREATE PROCEDURE [dbo].[CopySection]
AS
-- Declare a temporary variable table for storing the sections
DECLARE @.tblSection TABLE
(
id int,
parent_id int,
caption varchar(max),
)
DECLARE @.newAgendaID int, @.newSectionID int;
DECLARE @.tid int, @.tparent_id int, @.tcaption varchar(max);
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Copy the desired sections into the local temp variable table
INSERT INTO @.tblSection SELECT id, parent_id, caption FROM tblSection ORDER BY parent_id;
-- Using a cursor, step through all temp sections and add them to the tblSection but note its new ID
DECLARE c1 CURSOR FOR SELECT * FROM @.tblSection ORDER BY parent_id FOR UPDATE OF parent_id;
OPEN c1;
FETCH NEXT FROM c1 INTO @.tid, @.tparent_id, @.tcaption;
WHILE @.@.FETCH_STATUS = 0
BEGIN
-- Insert the new Section and record the identity
INSERT INTO tblSection (agenda_id, parent_id, caption) VALUES (@.tparent_id, @.tcaption);
SET @.newSectionID = SCOPE_IDENTITY();
-- Update the temp variable table with the new identity from the newly created real section in tblSection
-- Update all temp variable records to point to the new parent_id
UPDATE @.tblSection SET parent_id = @.newSectionID WHERE parent_id = @.tid;
FETCH NEXT FROM c1 INTO @.tid, @.tparent_id, @.tcaption;
END
CLOSE c1
DEALLOCATE c1
END
-
The critical "UPDATE @.tblSection" part doesnt seem to update the temp variable table with the @.newSectionID (the actual section identity obtained after inserting a real record into the tblSection table). So in the end the inserted records into tblSection still point to the incorrect parent_id instead of the copied record's parent_id.
Maybe I'm using CURSOR incorrectly or not setting a parameter so that it refreshes its recordset?
You can use the following query.. Here we are not using any cursor..
Declare @.Section Table
(
ParentId int,
Caption varchar(100)
)
Declare @.ParentId as int;
Declare @.NewParentId as int;
Declare @.Caption as varchar(100);
Insert into @.Section
Select Id,Caption from tblSection Where Parent_ID is NULL -- you can filter your desired id
While Exists(Select 1 From @.Section)
Begin
Select Top 1 @.ParentId = ParentId, @.Caption = Caption From @.Section;
Insert Into tblSection(parent_id, caption) values(null, @.Caption);
Select @.NewParentId =Scope_Identity();
Delete From @.Section Where ParentId = @.ParentId ;
Insert Into tblSection(parent_id, caption)
Select @.NewParentId, caption From tblSection Where parent_id = @.ParentId;
End
Select * From tblSection;
|||I have tried quantass 's code and it does not do the parentid properly as it keeps using the old parentid of the previous tree structure - can you please show me the actual code you got it working or how can it be solved please?
I really am in desperate need of getting one that actually works properly.
Thanks
|||Which version of SQL server are you running?|||I am using SQL server 2005 - I think I have tried to get it working but I don't know if this is the correct approach which I have modified quanass's sql.
-- Declare a temporary variable table for storing the sections
DECLARE @.tblSection TABLE
(
id int,
parent_id int,
caption varchar(max),
old_id int
)
DECLARE @.newSectionID int;
DECLARE @.tid int, @.tparent_id int, @.tcaption varchar(max),@.told_id int;
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Copy the desired sections into the local temp variable table
INSERT INTO @.tblSection SELECT id, parent_id, caption, old_id FROM tblSection ORDER BY parent_id;
-- Using a cursor, step through all temp sections and add them to the tblSection but note its new ID
DECLARE c1 CURSOR FOR SELECT * FROM @.tblSection ORDER BY parent_id FOR UPDATE OF parent_id;
OPEN c1;
FETCH NEXT FROM c1 INTO @.tid, @.tparent_id, @.tcaption,@.told_id;
WHILE @.@.FETCH_STATUS = 0
BEGIN
-- Insert the new Section and record the identity
INSERT INTO tblSection (parent_id, caption) VALUES (@.tparent_id, @.tcaption);
SET @.newSectionID = SCOPE_IDENTITY();
-- Update the temp variable table with the new identity from the newly created real section in tblSection
-- Update all temp variable records to point to the new parent_id
UPDATE @.tblSection SET parent_id = @.newSectionID, old_id = @.tid WHERE parent_id = @.tid;
FETCH NEXT FROM c1 INTO @.tid, @.tparent_id, @.tcaption,@.told_id;
END
CLOSE c1
DEALLOCATE c1
SELECT * FROM @.tblSection <from this point I tried to get the parentid done properly and not hanging onto the old parentID
WHILE EXISTS(SELECT 1 FROM @.tblSection)
BEGIN
SELECT @.tparent_id=parent_id,@.told_id=old_id FROM @.tblSection
UPDATE tblSection SET[parent_id] = @.tparent_id WHERE parent_id = @.told_id
DELETE FROM @.tblSection WHERE UpLevelID = @.tUpLevelID
END
END
I could do with some feedback and whether it can be improved and what can be changed on this?
Thanks
|||I have tried with the modified SQL as above and it did work with small data. But I found if I tried with 100 records - the parentid gets really messed up and doesn't look right.
I would really appreciate any help and examples or show me the corrections on my modified SQL please as I have spent a week struggling in vain to actually get it working properly.
ID ParentID MenuID Name
====================
1 0 1 sun
2 1 1 mars
3 2 1 charon
4 2 1 flubbie
5 3 1 blub
6 0 2 sun <-new menu as menuID of 1as it is a copy of it
7 6 2 mars
8 7 2 charon
9 7 2 flubbie
10 8 2 blub
Please help as I am in desperate situation on this. Thanks
|||I will give it a look and see what I can come up with; sorry I didn't respond yesterday. I've been off in DB2 land most of this week.|||This is my first pass and I feel like I didn't do a good job with it. It sure looks WAY more long-winded than your version. Also, I don't care for the WHILE loop in my stored procedure, but I have to somehow retrieve the IDENTITY values; nonetheless, it at least seems to to work. First, I defined this table for the mock-up:
create table dbo.jHierMenu
( ID integer identity (21, 1)
constraint pk_jHierMenu primary key,
ParentID integer null,
MenuID integer null,
[Name] varchar(20) not null
)
gocreate index jHierMenu_Menu_ndx
on dbo.jHierMenu (MenuID, ParentID, ID, [Name])
goinsert into dbo.jHierMenu values (0, 1, 'sun')
insert into dbo.jHierMenu values (21, 1, 'mars')
insert into dbo.jHierMenu values (22, 1, 'charon')
insert into dbo.jHierMenu values (22, 1, 'flubbie')
insert into dbo.jHierMenu values (23, 1, 'blub')
select * from dbo.jHierMenu
I then created a function that I could use as a building block:
create function dbo.relativeMenuHierarchy
( @.pm_MenuID integer
)
returns @.menuHierarchy table
( rid integer identity primary key,
ParentRid integer null,
ID integer not null,
ParentID integer null,
MenuID integer not null,
[Name] varchar (20) null,
hierLevel integer not null,
unique (hierLevel, rid)
)
as
beginif ( select count(*) from dbo.jHierMenu
where menuId = @.pm_menuID
) < 1
return;;with menuHierCTE
as
(
select id,
ParentID,
MenuID,
[Name],
0 as hierLevel
from dbo.jHierMenu
where MenuID = @.pm_menuID
and ParentID = 0
union all
select a.ID,
a.ParentID,
a.MenuID,
a.[Name],
cte.hierLevel + 1
from menuHierCTE as cte
inner join dbo.jHierMenu a
on a.menuId = @.pm_menuID
and a.parentID = cte.id
)
insert into @.menuHierarchy
select case when parentId = 0 then 0 else null end,
id,
parentId,
menuId,
[Name],
hierLevel
from menuHierCTEdeclare @.secondHierarchy table
( rid integer primary key,
ParentRid integer null,
ID integer not null,
ParentID integer null,
MenuID integer not null,
[Name] varchar (20) null,
hierLevel integer not null,
unique (hierLevel, rid)
)insert into @.secondHierarchy
select * from @.menuHierarchyupdate @.menuHierarchy
set ParentRid = a.rid
from @.secondHierarchy a
inner join @.menuHierarchy b
on a.hierLevel = b.hierLevel - 1
and a.id = b.parentId
inner join small_iterator (nolock) i
on iter = b.hierLevel
and iter <= ( select max(hierLevel)
from @.secondHierarchy
)return
end
go
select rid,
parentRid,
id,
parentId,
menuId,
[name],
hierLevel
from relativeMenuHierarchy (1);-- rid parentRid id parentId menuId name hierLevel
-- -- -- --
-- 1 0 21 0 1 sun 0
-- 2 1 22 21 1 mars 1
-- 3 2 23 22 1 charon 2
-- 4 2 24 22 1 flubbie 2
-- 5 3 25 23 1 blub 3
Once I had the function working, I assembled a stored procedure to perform the actual work:
create procedure dbo.replicateMenu
( @.pm_oldMenuId integer,
@.pm_newMenuId integer
)
asif exists
( select 0 from jHierMenu
where menuId = @.pm_newMenuId
)
begin
raiserror ('Menu ID ''%d'' is NOT a new menu id!', 0, 1, @.pm_newMenuID)
return 21001
enddeclare @.menuHierarchy table
( rid integer primary key,
ParentRid integer null,
ID integer null,
ParentID integer null,
MenuID integer not null,
[Name] varchar (20) null,
hierLevel integer not null,
unique (hierLevel, rid)
)insert into @.menuHierarchy
select rid,
parentRid,
null as ID,
null as ParentId,
menuId,
[name],
hierLevel
from dbo.relativeMenuHierarchy (@.pm_oldMenuID)declare @.nextRid integer
declare @.lastId integer
declare @.maxRid integerset @.maxRid = ( select max(rid) from @.menuHierarchy )
if @.maxRid = 0
return 0insert into dbo.jHierMenu
select 0 as parentId,
@.pm_newMenuId as [MenuId],
[Name]
from @.menuHierarchy
where rid = 1
set @.lastId = scope_identity()update @.menuHierarchy
set id = @.lastId,
parentId = 0
where rid = 1set @.nextRid = 1
while @.nextRid < @.maxRid
beginset @.nextRid = @.nextRid + 1
insert into dbo.jHierMenu
select p.id as ParentId,
@.pm_newMenuId as [MenuId],
a.[name]
from @.menuHierarchy a
inner join @.menuHierarchy p
on a.parentRid = p.rid
where a.rid = @.nextRidset @.lastId = scope_identity()
update @.menuHierarchy
set id = @.lastId,
parentId = h.parentId
from @.menuHierarchy a
inner join dbo.jHierMenu h
on h.id = @.lastId
and a.rid = @.nextRidend
return 0
go
exec replicateMenu 1, 101
select * from jHierMenu
-- ID ParentID MenuID Name
-- -- -- --
-- 21 0 1 sun
-- 22 21 1 mars
-- 23 22 1 charon
-- 24 22 1 flubbie
-- 25 23 1 blub-- 65 0 101 sun
-- 66 65 101 mars
-- 67 66 101 charon
-- 68 66 101 flubbie
-- 69 67 101 blubdelete from jHierMenu where menuId = 101
I will try this out with a 100 and 200 row test. I'm kinda fried right now and I must step back for at least a little while.
I tried the stored procedure with a 100-row menu and I feel better about all of this -- especially the function. I was able to use the function compare the two menus and verify that the replication had worked correctly. This also means that it would be relatively easy to create a "compareMenu" stored procedure or function. I started by truncating the mock-up table and inserting 100 random rows:
truncate table dbo.jHierMenu
goset identity_insert tempdb.dbo.jHierMenu ON
insert into dbo.jHierMenu
( id,
parentId,
menuId,
name
)
select 1 as id,
0 as parentId,
1 as menuId,
'Name 1' as [Name]insert into dbo.jHierMenu
( id,
parentId,
menuId,
name
)
select iter as id,
floor(1 + (cast (iter as float) - 1.99999) * dbo.randValue(iter))
as parentId,
1 as menuId,
'Name ' + convert (varchar (5), iter) as [Name]
from small_iterator
where iter > 1
and iter <= 100
goset identity_insert tempdb.dbo.jHierMenu Off
go
select * from dbo.jHierMenu order by id
-- ID ParentID MenuID Name
-- -- --
-- 1 0 1 Name 1
-- 2 1 1 Name 2
-- 3 1 1 Name 3
-- 4 1 1 Name 4
-- 5 3 1 Name 5
-- 6 4 1 Name 6
-- 7 5 1 Name 7
-- ...
-- 99 84 1 Name 99
-- 100 12 1 Name 100
I then ran the "replicateMenu" stored procedure and then ran the query that follows to verify that the new menu was identical in structure to the old menu:
|||set nocount on
--delete from dbo.jHierMenu where menuId = 101
exec replicateMenu 1, 101-- -
-- Uncomment the AND statement if you want to display
-- only the exceptions.
-- -
select a.rid,
a.[name],
b.rid,
b.[name]
from relativeMenuHierarchy (1) a
inner join relativeMenuHierarchy (101) b
on a.rid = b.rid
-- and a.name <> b.name-- rid name rid name
-- - -
-- 1 Name 1 1 Name 1
-- 2 Name 2 2 Name 2
-- 3 Name 3 3 Name 3
-- ...
-- 99 Name 84 99 Name 84
-- 100 Name 99 100 Name 99
Hi
I had read through your examples and it seems much cleaner and efficient than mine (a compliment). I have tested out my stored procedure several times and it does work (at least I think it does). However I am going try yours as well and test it out again.
I also realise supposing someone comes a long and deletes an item and the rest of items becomes obselete if you like as the first item is missing so the uplevel gets skewed up. So if they copy that menu with the missing item and the rest of the items with obselete uplevel, theoretically, the copied menu would have the rest of the items with the old obselete uplevelID - would that break the stored procedure coding or mess the structure when copying a menu? I noticed it does happen with my old stored proc - could that easily be remedied?
I really appreciate the time and effort you have put in this stored procedure and my gratitude of thanks goes towards you. I found what you have done with the stored procedure and testing has been a big lesson for me and hopefully I will improve my 'thinking out of the box'.
Thanks again, will keep you posted to let you know how I get on with the testing on this.
Tuesday, March 27, 2012
Help with Case Statement
I have the following code in which I need to check something in the ELSE. The problem is how to form it correctly. I could use a cursor I guess to transverse through the records.
In the Else, I want to:
1) Check the count of the results of my statement. IF > 1 then check to see if m.original is between lowlimit and highlimit for any of those records found
2) If m.original is between the lowlimit and highlimit, then select Fee1 from FeeScheduleDetails
m.original and m.FeeSchedule is out here somewhere, just know this...it's part of the query that you don't see
CASE WHEN Len(c.FeeSchedule) < 3 then
CONVERT(int, c.feeSchedule)
ELSE
Select Count(*) FROM FeeScheduleDetails fd
INNER JOIN Master m ON m.FeeSchedule = fd.code
IF Count(*) > 3
Check to see if m.original is BETWEEN fd.lowlimit AND fd.highlimit
If yes, then bring me back fee1, if no then just bring me back m.FeeSchedule
END AS FeeSchedule
Master
FeeSchedule
FeeScheduleDetails
-
Code
LowLimit
HighLimit
Fee1
thanks for the heads up. Here's the entire query...and a new attept at fee1
INSERT INTO ReportingServer.dbo.DCR
SELECT
m.customer,
c.name,
c.customer,
c.state,
CASE WHEN Len(c.FeeSchedule) < 3 THEN
CONVERT(int, c.feeSchedule)
WHEN Len(c.FeeSchedule) > 3 THEN
SELECT fd.Fee1 FROM FeeScheduleDetails fd
where c.feeSchedule = fd.code AND m.original BETWEEN fd.LowLimit AND fd.HighLimit
ELSE
CONVERT(int, c.feeSchedule)
END AS FeeSchedule,
m.Branch,
CASE WHEN ph.batchtype = 'PUR' OR ph.batchtype = 'PAR' OR ph.batchtype = 'PCR' Then
(ph.totalpaid - ph.ForwardeeFee)
ELSE
0.00
END AS [Posted Amount],
ph.systemmonth,
ph.datepaid,
ph.totalpaid,
ph.batchtype,
m.desk,
0 AS [New Old CC],
0 AS [New Old PDC],
'In-House' AS Type,
1 AS Active,
ph.UID,
m.number,
dc.amount CC,
p.amount AS PDC,
m.original,
CONVERT(money, ph.OverPaidAmt),
0,
0,
''
FROM dbo.Master m (NOLOCK) LEFT JOIN dbo.payhistory ph ON m.number = ph.number
LEFTJOIN dbo.DebtorCreditCards dc ON dc.number = m.number
LEFTJOIN dbo.pdc p ON p.number = m.number
LEFTJOIN dbo.Customer c ON c.Customer = m.Customer
LEFTJOIN Apex_ReportingServer.dbo.FeeGoal fg ON fg.CustomerID = c.Customer
GROUP BYm.customer,
c.name,
c.customer,
c.state,
c.FeeSchedule,
m.Branch,
ph.OverPaidAmt,
ph.systemmonth,
ph.datepaid,
ph.totalpaid,
ph.batchtype,
m.desk,
ph.UID,
m.number,
dc.amount,
p.amount,
m.original ,
ph.systemmonth,
ph.systemyear,
ph.ForwardeeFee
HAVINGph.systemmonth = datepart(mm, getdate()) AND ph.batchtype <> 'DA' AND
ph.batchtype <> 'DAR' AND ph.systemyear = datepart(yy, getdate())
AND (c.Name is not null AND c.Name <> '')
ORDER BY m.customer
|||? Hi dba123, Thanks - but you didn't post CREATE TABLE and INSERT statements, so I still can't test any code, nor see what exactly you try to do. Anyway - I'll respond to your other post; it looks to be a simplified version of this problem. If you do need more help in this thread, then add some CREATE TABLE and INSERT statements and expected results, and I'll have a look at it. -- Hugo Kornelis, SQL Server MVP <dba123@.discussions.microsoft.com> schreef in bericht news:662f6401-ea73-4c37-a98e-dd9267c0ed2c@.discussions.microsoft.com... thanks for the heads up. Here's the entire query...and a new attept at fee1 INSERT INTO ReportingServer.dbo.DCR SELECT m.customer, c.name, c.customer, c.state, CASE WHEN Len(c.FeeSchedule) < 3 THEN CONVERT(int, c.feeSchedule) WHEN Len(c.FeeSchedule) > 3 THEN SELECT fd.Fee1 FROM FeeScheduleDetails fd where c.feeSchedule = fd.code AND m.original BETWEEN fd.LowLimit AND fd.HighLimit ELSE CONVERT(int, c.feeSchedule) END AS FeeSchedule, m.Branch, CASE WHEN ph.batchtype = 'PUR' OR ph.batchtype = 'PAR' OR ph.batchtype = 'PCR' Then (ph.totalpaid - ph.ForwardeeFee) ELSE 0.00 END AS [Posted Amount], ph.systemmonth, ph.datepaid, ph.totalpaid, ph.batchtype, m.desk, 0 AS [New Old CC], 0 AS [New Old PDC], 'In-House' AS Type, 1 AS Active, ph.UID, m.number, dc.amount CC, p.amount AS PDC, m.original, CONVERT(money, ph.OverPaidAmt), 0, 0, '' FROM dbo.Master m (NOLOCK) LEFT JOIN dbo.payhistory ph ON m.number = ph.number LEFT JOIN dbo.DebtorCreditCards dc ON dc.number = m.number LEFT JOIN dbo.pdc p ON p.number = m.number LEFT JOIN dbo.Customer c ON c.Customer = m.Customer LEFT JOIN Apex_ReportingServer.dbo.FeeGoal fg ON fg.CustomerID = c.Customer GROUP BY m.customer, c.name, c.customer, c.state, c.FeeSchedule, m.Branch, ph.OverPaidAmt, ph.systemmonth, ph.datepaid, ph.totalpaid, ph.batchtype, m.desk, ph.UID, m.number, dc.amount, p.amount, m.original , ph.systemmonth, ph.systemyear, ph.ForwardeeFee HAVING ph.systemmonth = datepart(mm, getdate()) AND ph.batchtype <> 'DA' AND ph.batchtype <> 'DAR' AND ph.systemyear = datepart(yy, getdate()) AND (c.Name is not null AND c.Name <> '') ORDER BY m.customer|||So are you asking for my table structure then? The table has already been created...so are you asking for the erd ?|||I am not sure what you are asking. I have also never seen a CASE statement used in this way. CASE statements are always used within a SELECT clause to select a result value to display in the column based on the value in a particular row. SQL has an IF condition of form:
IF.....
BEGIN
END
ELSE
BEGIN
END
Firstly I suggest you use IF that instead. Is your IF statement returning multiple values, or just one value? If it is just returning one value (and with a count(*) you normally only return one valuer, unless using a GROUP BY) then use and IF, otherwise use a case statement. IF example below)
declare @.result int
declare @.lowlimit int
declare @.highlimit int
IF Len(c.FeeSchedule) < 3
BEGIN
set @.result = CONVERT(int, c.feeSchedule)
END
ELSE
work out @.lowlimit and @.highlimit here.....
delcare @.cnt int
Select @.cnt = Count(*) FROM FeeScheduleDetails fd
INNER JOIN Master m ON m.FeeSchedule = fd.code
IF @.cntBETWEEN @.lowlimit AND @.highlimit
BEGIN
@.result = (get Fee1......)
END
ELSE
BEGIN
@.result = (get m.FeeSchedule.....)
END
END
Otherwise, if you want the second conditional to be a CASE statement, you will need to rewrite it accordingly
Clarity Consulting
|||I don't think you can do a select statment inside of a CASE statement. Store the result in a variable, and then select that in the CASE statement instead if possible. Otherwise, get the value from a JOIN instead, then you just need to select the column in the CASE...WHEN .. THEN statement.|||? Hi dba123, Sorry for the delayed reply... >>So are you asking for my table structure then? The table has already been created...so are you asking for the erd ? What I'm askking you for is a bunch of statements that I can copy and paste into Query Analyzer and run to recreate the problem. To give you a very simplified example: instead of asking "how to get the lowest wage for each department", you'd have to post some SQL: CREATE TABLE Personnel (EmpID int NOT NULL PRIMARY KEY, DeptID int NOT NULL, Wage decimal(7,2) NOT NULL) go INSERT INTO Personnel (EmpID, DeptID, Wage) VALUES (1, 1, 20000) INSERT INTO Personnel (EmpID, DeptID, Wage) VALUES (2, 1, 30000) INSERT INTO Personnel (EmpID, DeptID, Wage) VALUES (3, 2, 15000) INSERT INTO Personnel (EmpID, DeptID, Wage) VALUES (4, 3, 20000) go And then, you'd add the required results: DeptID LowestWage 1 20000 2 15000 3 20000 Anyone can now copy the SQL statements, execute them in a test database, try some queries and finally come up with this reply: SELECT DeptID, MIN(Wage) AS LowestWage FROM Personnel GROUP BY DeptID Of course, the example above is pretty basic. Your questions (at least the ones I've seen here) are a lot more complex. Trying to answer them without knowing exactly how the tables look (i.e. columns, datatypes, constraints, indexes, defaults, ... everything you'd see in a CREATE TABLE statement), what kind of data is in them (i.e. the INSERT statements) and what results you expect to get makes it more an exercise at guessing, or even mind reading, than an exercise in writing SQL. I'm pretty good at writing SQL. I think I help a lot of people with my skills in this and other forums and groups. But my clairvoyance skills are lousy. In other words: if you don't explain the problem clear enough, you're likely to get no answer or a wrong answer from me - and probably from others as well. From experience, I know that most probles are best explained by posting CREATE TABLE statements, INSERT statements, expected results and a short explanation. Check out www.aspfaq.com/5006 for more information about this and for some techniques that can help you assemble the information for your posts. I hope this helps. -- Hugo Kornelis, SQL Server MVP|||thanks, I was using the case statement to determine which to return back as FeeSchedule. It's dependent on the lenght of a certain field. I the field was>3 I needed to do a lookup else, juse use that field.|||thanksNNTP User
. Sometimes I don't have all those statements created because the statement I'm working on is it and is my only attempt/approach at the time! Yes, I could have posted some data examples though. Thanks for your explanation.
Monday, March 19, 2012
Help with a CURSOR
to me every table that has a different row count from one database to
another. I believe the best way to accomplish this is using a CURSOR to
fetch through the tables in the DB and print those where the record count
differs. Here is what I'm trying to do:
DECLARE @.Table nvarchar(40)
DECLARE Table_CURSOR CURSOR FOR
select sysobjects.name
from sysobjects, syscolumns, systypes
where syscolumns.id = sysobjects.id and syscolumns.xtype
= systypes.xtype
and sysobjects.xtype = 'U'
group by sysobjects.name
order by sysobjects.name
OPEN Table_CURSOR
FETCH NEXT FROM Table_CURSOR
INTO @.Table
WHILE @.@.FETCH_STATUS = 0
BEGIN
IF (SELECT COUNT(*) FROM Database1..[@.Table] WHERE ID NOT IN (SELECT ID
FROM Database2..[@.Table])) > 1
BEGIN
Print @.Table
END
FETCH NEXT FROM Table_CURSOR
INTO @.Table
END
CLOSE Table_CURSOR
DEALLOCATE Table_CURSOR
However, I get errors on "Invalid object name 'Database1..@.Table' and
"Invalid object name 'Database2..@.Table'.
I've tried without the bracket signs around [@.Table] as well, but then get
an error "Incorrect Syntax near '@.Table'.
Any ideas? Is there an easier way to achieve this? Thanks in advance,
JasonThe problem is that you cannot substitute variables for object names (like
databases or tables). However, you can execute dynamic sql. Here is a good
article. Also, useful is the undocumented sp_msforeachtable procedure.
http://www.databasejournal.com/feat...cle.php/1438931
"Jason" <jason@.nospam.com> wrote in message
news:OTGTuNX5FHA.2036@.TK2MSFTNGP14.phx.gbl...
> Here's my dilema. I'm trying to create a SQL script that will report back
> to me every table that has a different row count from one database to
> another. I believe the best way to accomplish this is using a CURSOR to
> fetch through the tables in the DB and print those where the record count
> differs. Here is what I'm trying to do:
> DECLARE @.Table nvarchar(40)
> DECLARE Table_CURSOR CURSOR FOR
> select sysobjects.name
> from sysobjects, syscolumns, systypes
> where syscolumns.id = sysobjects.id and syscolumns.xtype
> = systypes.xtype
> and sysobjects.xtype = 'U'
> group by sysobjects.name
> order by sysobjects.name
> OPEN Table_CURSOR
> FETCH NEXT FROM Table_CURSOR
> INTO @.Table
> WHILE @.@.FETCH_STATUS = 0
> BEGIN
> IF (SELECT COUNT(*) FROM Database1..[@.Table] WHERE ID NOT IN (SELECT ID
> FROM Database2..[@.Table])) > 1
> BEGIN
> Print @.Table
> END
> FETCH NEXT FROM Table_CURSOR
> INTO @.Table
> END
> CLOSE Table_CURSOR
> DEALLOCATE Table_CURSOR
> However, I get errors on "Invalid object name 'Database1..@.Table' and
> "Invalid object name 'Database2..@.Table'.
> I've tried without the bracket signs around [@.Table] as well, but then get
> an error "Incorrect Syntax near '@.Table'.
> Any ideas? Is there an easier way to achieve this? Thanks in advance,
> Jason
>
Friday, February 24, 2012
Help setting up a trace for a sp
I haven't really used the trace program much. I am having a problem with
a sp that we created it seems to skip records during the cursor. I want to
setup a trace on that specific store procedure only is there a way to do
this? Thanks in advance. The name of the sp is called "datacollection"
Jake
I'm a little confused as to what you want to trace. Would you explain
more? Sounds like you want to trace the progress through a SP. Meaning you
want to show every command it executes? Sounds like you what you want to do
is use the Transact-SQL debugger. Is this correct? I have not used the
T-SQL debugger, so I really can't help you if this is what you are looking
for. But here is an msdn article that might get you started:
http://msdn.microsoft.com/library/de...qldebugger.asp
----
Need SQL Server Examples check out my website at
http://www.geocities.com/sqlserverexamples
"Jake" <rondican@.hotmail.com> wrote in message
news:O7WS7hTWEHA.2940@.TK2MSFTNGP09.phx.gbl...
> Hello,
> I haven't really used the trace program much. I am having a problem
with
> a sp that we created it seems to skip records during the cursor. I want to
> setup a trace on that specific store procedure only is there a way to do
> this? Thanks in advance. The name of the sp is called "datacollection"
> Jake
>
|||Gregory,
I was looking at the profiler tool that comes with SQL. You are correct
in that I want to see each line being processed for the sp. I will take a
look at this and see if I can tweak it to work for our needs. Thanks.
Jake
"Gregory A. Larsen" <greg.larsen@.netzero.com> wrote in message
news:O3SQ8uTWEHA.3012@.tk2msftngp13.phx.gbl...
> I'm a little confused as to what you want to trace. Would you explain
> more? Sounds like you want to trace the progress through a SP. Meaning
you
> want to show every command it executes? Sounds like you what you want to
do
> is use the Transact-SQL debugger. Is this correct? I have not used the
> T-SQL debugger, so I really can't help you if this is what you are looking
> for. But here is an msdn article that might get you started:
>
http://msdn.microsoft.com/library/de...qldebugger.asp
>
> --
> ----
--
> ----
--[vbcol=seagreen]
> --
> Need SQL Server Examples check out my website at
> http://www.geocities.com/sqlserverexamples
> "Jake" <rondican@.hotmail.com> wrote in message
> news:O7WS7hTWEHA.2940@.TK2MSFTNGP09.phx.gbl...
> with
to
>
|||You might also want to review the "Transact-SQL Debugger Window" topic in
BOL.
----
Need SQL Server Examples check out my website at
http://www.geocities.com/sqlserverexamples
"Jake" <rondican@.hotmail.com> wrote in message
news:OM8ThzTWEHA.1048@.tk2msftngp13.phx.gbl...
> Gregory,
> I was looking at the profiler tool that comes with SQL. You are
correct[vbcol=seagreen]
> in that I want to see each line being processed for the sp. I will take a
> look at this and see if I can tweak it to work for our needs. Thanks.
> Jake
> "Gregory A. Larsen" <greg.larsen@.netzero.com> wrote in message
> news:O3SQ8uTWEHA.3012@.tk2msftngp13.phx.gbl...
> you
to[vbcol=seagreen]
> do
looking
>
http://msdn.microsoft.com/library/de...qldebugger.asp[vbcol=seagreen]
> ----
> --
> ----
> --
problem[vbcol=seagreen]
want[vbcol=seagreen]
> to
do
>
Help setting up a trace for a sp
I haven't really used the trace program much. I am having a problem with
a sp that we created it seems to skip records during the cursor. I want to
setup a trace on that specific store procedure only is there a way to do
this? Thanks in advance. The name of the sp is called "datacollection"
JakeI'm a little confused as to what you want to trace. Would you explain
more? Sounds like you want to trace the progress through a SP. Meaning you
want to show every command it executes? Sounds like you what you want to do
is use the Transact-SQL debugger. Is this correct? I have not used the
T-SQL debugger, so I really can't help you if this is what you are looking
for. But here is an msdn article that might get you started:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconthetsqldebugger.asp
----
----
--
Need SQL Server Examples check out my website at
http://www.geocities.com/sqlserverexamples
"Jake" <rondican@.hotmail.com> wrote in message
news:O7WS7hTWEHA.2940@.TK2MSFTNGP09.phx.gbl...
> Hello,
> I haven't really used the trace program much. I am having a problem
with
> a sp that we created it seems to skip records during the cursor. I want to
> setup a trace on that specific store procedure only is there a way to do
> this? Thanks in advance. The name of the sp is called "datacollection"
> Jake
>|||Gregory,
I was looking at the profiler tool that comes with SQL. You are correct
in that I want to see each line being processed for the sp. I will take a
look at this and see if I can tweak it to work for our needs. Thanks.
Jake
"Gregory A. Larsen" <greg.larsen@.netzero.com> wrote in message
news:O3SQ8uTWEHA.3012@.tk2msftngp13.phx.gbl...
> I'm a little confused as to what you want to trace. Would you explain
> more? Sounds like you want to trace the progress through a SP. Meaning
you
> want to show every command it executes? Sounds like you what you want to
do
> is use the Transact-SQL debugger. Is this correct? I have not used the
> T-SQL debugger, so I really can't help you if this is what you are looking
> for. But here is an msdn article that might get you started:
>
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconthetsqldebugger.asp
>
> --
> ----
--
> ----
--
> --
> Need SQL Server Examples check out my website at
> http://www.geocities.com/sqlserverexamples
> "Jake" <rondican@.hotmail.com> wrote in message
> news:O7WS7hTWEHA.2940@.TK2MSFTNGP09.phx.gbl...
> > Hello,
> >
> > I haven't really used the trace program much. I am having a problem
> with
> > a sp that we created it seems to skip records during the cursor. I want
to
> > setup a trace on that specific store procedure only is there a way to do
> > this? Thanks in advance. The name of the sp is called "datacollection"
> >
> > Jake
> >
> >
>|||You might also want to review the "Transact-SQL Debugger Window" topic in
BOL.
--
----
----
--
Need SQL Server Examples check out my website at
http://www.geocities.com/sqlserverexamples
"Jake" <rondican@.hotmail.com> wrote in message
news:OM8ThzTWEHA.1048@.tk2msftngp13.phx.gbl...
> Gregory,
> I was looking at the profiler tool that comes with SQL. You are
correct
> in that I want to see each line being processed for the sp. I will take a
> look at this and see if I can tweak it to work for our needs. Thanks.
> Jake
> "Gregory A. Larsen" <greg.larsen@.netzero.com> wrote in message
> news:O3SQ8uTWEHA.3012@.tk2msftngp13.phx.gbl...
> > I'm a little confused as to what you want to trace. Would you explain
> > more? Sounds like you want to trace the progress through a SP. Meaning
> you
> > want to show every command it executes? Sounds like you what you want
to
> do
> > is use the Transact-SQL debugger. Is this correct? I have not used the
> > T-SQL debugger, so I really can't help you if this is what you are
looking
> > for. But here is an msdn article that might get you started:
> >
> >
>
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconthetsqldebugger.asp
> >
> >
> > --
> >
> ----
> --
> ----
> --
> > --
> >
> > Need SQL Server Examples check out my website at
> > http://www.geocities.com/sqlserverexamples
> > "Jake" <rondican@.hotmail.com> wrote in message
> > news:O7WS7hTWEHA.2940@.TK2MSFTNGP09.phx.gbl...
> > > Hello,
> > >
> > > I haven't really used the trace program much. I am having a
problem
> > with
> > > a sp that we created it seems to skip records during the cursor. I
want
> to
> > > setup a trace on that specific store procedure only is there a way to
do
> > > this? Thanks in advance. The name of the sp is called "datacollection"
> > >
> > > Jake
> > >
> > >
> >
> >
>
Help setting up a trace for a sp
I haven't really used the trace program much. I am having a problem with
a sp that we created it seems to skip records during the cursor. I want to
setup a trace on that specific store procedure only is there a way to do
this? Thanks in advance. The name of the sp is called "datacollection"
JakeI'm a little confused as to what you want to trace. Would you explain
more? Sounds like you want to trace the progress through a SP. Meaning you
want to show every command it executes? Sounds like you what you want to do
is use the Transact-SQL debugger. Is this correct? I have not used the
T-SQL debugger, so I really can't help you if this is what you are looking
for. But here is an msdn article that might get you started:
nthetsqldebugger.asp" target="_blank">http://msdn.microsoft.com/library/d...sqldebugger.asp
----
----
--
Need SQL Server Examples check out my website at
http://www.geocities.com/sqlserverexamples
"Jake" <rondican@.hotmail.com> wrote in message
news:O7WS7hTWEHA.2940@.TK2MSFTNGP09.phx.gbl...
> Hello,
> I haven't really used the trace program much. I am having a problem
with
> a sp that we created it seems to skip records during the cursor. I want to
> setup a trace on that specific store procedure only is there a way to do
> this? Thanks in advance. The name of the sp is called "datacollection"
> Jake
>|||Gregory,
I was looking at the profiler tool that comes with SQL. You are correct
in that I want to see each line being processed for the sp. I will take a
look at this and see if I can tweak it to work for our needs. Thanks.
Jake
"Gregory A. Larsen" <greg.larsen@.netzero.com> wrote in message
news:O3SQ8uTWEHA.3012@.tk2msftngp13.phx.gbl...
> I'm a little confused as to what you want to trace. Would you explain
> more? Sounds like you want to trace the progress through a SP. Meaning
you
> want to show every command it executes? Sounds like you what you want to
do
> is use the Transact-SQL debugger. Is this correct? I have not used the
> T-SQL debugger, so I really can't help you if this is what you are looking
> for. But here is an msdn article that might get you started:
>
.asp" target="_blank">http://msdn.microsoft.com/library/d...ger
.asp
>
> --
> ----
--
> ----
--
> --
> Need SQL Server Examples check out my website at
> http://www.geocities.com/sqlserverexamples
> "Jake" <rondican@.hotmail.com> wrote in message
> news:O7WS7hTWEHA.2940@.TK2MSFTNGP09.phx.gbl...
> with
to[vbcol=seagreen]
>|||You might also want to review the "Transact-SQL Debugger Window" topic in
BOL.
----
----
--
Need SQL Server Examples check out my website at
http://www.geocities.com/sqlserverexamples
"Jake" <rondican@.hotmail.com> wrote in message
news:OM8ThzTWEHA.1048@.tk2msftngp13.phx.gbl...
> Gregory,
> I was looking at the profiler tool that comes with SQL. You are
correct
> in that I want to see each line being processed for the sp. I will take a
> look at this and see if I can tweak it to work for our needs. Thanks.
> Jake
> "Gregory A. Larsen" <greg.larsen@.netzero.com> wrote in message
> news:O3SQ8uTWEHA.3012@.tk2msftngp13.phx.gbl...
> you
to[vbcol=seagreen]
> do
looking[vbcol=seagreen]
>
.asp" target="_blank">http://msdn.microsoft.com/library/d...ger
.asp
> ----
> --
> ----
> --
problem[vbcol=seagreen]
want[vbcol=seagreen]
> to
do[vbcol=seagreen]
>