Please Need Rescue- Complex Update Logic Swap

May 14, 2008

please need rescue- complex update logic
this is my table







1

2

3

4

5

EMPID
fld1
fld11
fld111
fld2
fld22
fld222
fld3
fld33
fld4
fld44

fld444
fld5
fld55
fld555


















1111

A

B

C

7

8

9

G

H

I

J

K

L

M

N


















2222

N

M

L

K

J

I

H

G

F

E

D

C

B

A


















3333

1

2

3

A

B

C

C

E

Y

I

O

W

Y

P




















i need to update for example the eployee 1111 with employee 3333
but with swap ( take the value of employee 1111 in field- fld2,fld22,fld222 and swap value between employee 3333
in field- fld2,fld22,fld222 )



Code Snippet
---update eployee 1111 with employee 3333
-so
if i put the value 2
than ------------------ swap value between 2 employee
set empid1= 1111
set empid2=3333
value_swap=2
if value_swap=2
than
update fld2,fld22,fld222
with fld2,fld22,fld222
------------------- take the value of employee 1111 in field- fld2,fld22,fld222 and swap value between employee 3333
--------------------in field- fld2,fld22,fld222








value_swap

=1

=2

=3

=4

=5

EMPID
fld1
fld11
fld111
fld2
fld22
fld222
fld3
fld33
fld4
fld44

fld444
fld5
fld55
fld555


















1111

A

B

C

A

B

C

G

H

I

J

K

L

M

N


















2222

N

M

L

K

J

I

H

G

F

E

D

C

B

A


















3333

1

2

3

7

8

9

C

E

Y

I

O

W

Y

P



















Code Snippet
---update eployee 2222 with employee 1111
-so
if i put the value 5
than ------------------ swap value between 2 employees
set empid1= 1111
set empid2=2222
value_swap=5
if value_swap=5
than
update fld5,fld55,fld555
with fld5,fld55,fld555
------------------- take the value of employee 1111 in field- fld5,fld55,fld555 and swap value between employee 3333
--------------------in field- fld5,fld55,fld555













=1

=2

=3

=4

=5

EMPID
fld1
fld11
fld111
fld2
fld22
fld222
fld3
fld33
fld4
fld44

fld444
fld5
fld55
fld555


















1111

A

B

C

7

8

9

G

H

I

J

K

W

Y

P


















2222

N

M

L

K

J

I

H

G

F

E

D

C

B

A


















3333

1

2

3

A

B

C

C

E

Y

I

O

L

M

N















TNX FOR ALL THE HELP I GET IN THIS Forum

View 7 Replies


ADVERTISEMENT

Please Help With Complex Update Statement Logic

Nov 8, 2006

hi.I am having probelms with an update statement. every timei run it, "every" row updates, not just the one(s) intended.so, here is what i have. i have tried this with both AND and ORand neither seem to work.i dont know why this is elluding me, but i'd appreciate help with thesolution.thanks.UPDATE addSET add_s = 1WHERE add.add_status = 0 and add.add_email = 'mags23@rice.edu'or add_s in(SELECT a.add_sFROM add a, edit eWHERE a.email_address = e.email_addressand e.public_name = 'professor')

View 22 Replies View Related

Complex Sql Logic... Need Help

Feb 15, 2007

okay;

i have a table called tblSlots
tblSlots is a list of Start datetimes and End datetimes.
every day has the same list of 10 slots.

tblSlots:
PKSlotINDEX
datStartTime
datEndTime

then i have a table called tblPersons

tblPersons:
PKPersonINDEX
txtLast
txtFirst

then i have a table called tblSchedule

tblSchedule:
PKScheduleINDEX
fkSlotINDEX
fkPersonINDEX

i want to write a query that takes any one specific person's schedule for an entire specific day, adds an arbitrary number of days to datStartTime, and finally inserts the PKSlotINDEX corresponding to the calcultated StartTime and fkPersonINDEX.

wow complicated isnt it...

the goal is to take the schedule of one day for one person and copy it to another day; i can scrap my current layout if necessary.


thanks!

View 1 Replies View Related

Looking For The Change Using A Complex Logic

Apr 25, 2008

I have records like below

ID Facility Procedure Date Action

1001 A 888 07/01/2007

1002 A 888 07/31/2007

1003 B 888 09/01/2007

1004 B 888 09/15/2007

1005 B 888 10/11/2007

1006 B 999 10/24/2007

1007 B 777 10/25/2007

1008 B 777 10/30/2007



I have to update an action column based on the business logic below.

1. if there is a change in FACILITY with the same PROCEDURE and the DATE between new facility and the date of previous record is less than 30 days ,

then update ACTION = TP

2. if there is a change in procedure , update Action = TS

3. is there is a change in FACILITY but have different PROCEDURE, then NO UPDATE



The output should look like below:

ID 1003 has TP because the FACILITY has changed with the same PROCEDURE compare to the previous record and the DATE is less than 30 days

ID 1006 has TS because the PROCEDURE has changed compare to previous record

ID 1009 didn’t get changed because it has different PROCEDURE even though FACILITY got changed...



ID Facility Procedure Date Action

1001 A 888 07/01/2007

1002 A 888 07/31/2007

1003 B 888 08/05/2007 TP

1004 B 888 09/15/2007

1005 B 888 10/11/2007

1006 B 999 10/24/2007 TS

1007 B 999 10/25/2007

1008 B 777 10/30/2007 TS

1009 D 666 11/07/2007



What is the best way to do this? Do I have to use a cursor to compare each record? Can you sow me some code examples?

View 7 Replies View Related

Help Needed In This Complex Logic

Mar 28, 2008

Table:GRoupAllocation
______________________
GroupId (Primarykey)
GroupName

Table:SystemAllocation
_______________________
SystemId(Primarykey)
SystemName
GroupId (foreignkey)

Table:DeviceAllocation
_______________________
DeviceId (Primarykey)
DeviceName
SystemId (foreignkey)
_______________________

Table:SensorAllocation
_______________________
SensorId (Primarykey)
SensorName
GroupId (Primarykey)
SystemId (foreignkey)
_______________________

Table:GRoupAllocation
______________________
GroupId GroupName
1 Group1
2 Group2
3 GRoup3
4 Group4

Table:SystemAllocation
___________________________
SystemId SystemName GroupId
1 system1 1
2 system2 2
3 system3 3
4 system4 2
5 system5 1

Table:DeviceAllocation
___________________________
DeviceId DeviceName SystemId
1 Device1 1
2 Device3 3
3 Device4 2

Table:SensorAllocation
____________________________________________
SensorId SensorName GroupId SystemId DeviceId
1 sensor1 1 1 1
3 sensor3 2 2
4 sensor4 3 3 3

my results should be like this:


Results:
___________________________________________________________________
GroupName SystemName DeviceName SensorName
___________________________________________________________________
Group1 system1 Device1 sensor1
Group1 null null sensor2
GRoup2 system2 null sensor3
GRoup2 system4 null null
Group3 system3 Device3 sensor4
Group4 null null null

so i need to populate the results in treeview.my treeview looks lika this:

Group1
|____System1
|________Device1
|_______sensor1

|_______system5

Group2
|____System2
|________Device1
|_______sensor1


|____System4
|____Device4

like this i need to populate. i need to show all the groupname and belonging systemName and belonging devicename and belonging sensorname

so please give me query for this complex operation please
criteria's
1.GRoup can have systems and system can have devices and device can have sensors
2.GRoup can have systems and systems can have sensors[no device]
3.GRoup can have systems and systems can have devices [no sensor]
4.GRoup can only have system [no device, no sensor]
5.GRoup can have only sensor[no system, no device]
so please

View 5 Replies View Related

Complex Date Logic - Help Needed

Sep 21, 2004

This concerns eligibility healthcare information. A member can have multiple rows in the table showing they are eligible for different date ranges with different health plans. eff_date and term_date are the fields in this table. Term_date can be NULL.

I need a WHERE statement that shows members
1) eligible between 1/1/2004 and 8/15/2004

(term_date is null or term_date >= '8/15/2004')
and eff_date <='1/1/2004'

2) members are allowed only one gap in this timeframe of up to 45 days. *NEED HELP

3) a gap of 1 day should not be counted as a gap in enrollment. *NEED HELP

Any help on #2 and #3 would be appreciated.

View 1 Replies View Related

Query Needed For Complex Logic

Mar 28, 2008

Table:GRoupAllocation
______________________
GroupId (Primarykey)
GroupName

TableystemAllocation
_______________________
SystemId(Primarykey)
SystemName
GroupId (foreignkey)

TableeviceAllocation
_______________________
DeviceId (Primarykey)
DeviceName
SystemId (foreignkey)
_______________________

TableensorAllocation
_______________________
SensorId (Primarykey)
SensorName
GroupId (foreignkey)
SystemId (foreignkey)
deviceid(foreignkey)
_______________________

Table:GRoupAllocation
______________________
GroupId GroupName
1 Group1
2 Group2
3 GRoup3
4 Group4

TableystemAllocation
___________________________
SystemId SystemName GroupId
1 system1 1
2 system2 2
3 system3 3
4 system4 2
5 system5 1

TableeviceAllocation
___________________________
DeviceId DeviceName SystemId
1 Device1 1
2 Device3 3
3 Device4 2

TableensorAllocation
____________________________________________
SensorId SensorName GroupId SystemId DeviceId
1 sensor1 1 1 1
3 sensor3 2 2
4 sensor4 3 3 3

my results should be like this:


Results:
___________________________________________________________________
GroupName SystemName DeviceName SensorName
___________________________________________________________________
Group1 system1 Device1 sensor1
Group1 null null sensor2
GRoup2 system2 null sensor3
GRoup2 system4 null null
Group3 system3 Device3 sensor4
Group4 null null null

so i need to populate the results in treeview.my treeview looks lika this:

Group1
|____System1
|________Device1
|_______sensor1

|_______system5

Group2
|____System2
|________Device1
|_______sensor1


|____System4
|____Device4

like this i need to populate. i need to show all the groupname and belonging systemName and belonging devicename and belonging sensorname

so please give me query for this complex operation please
criteria's
1.GRoup can have systems and system can have devices and device can have sensors
2.GRoup can have systems and systems can have sensors[no device]
3.GRoup can have systems and systems can have devices [no sensor]
4.GRoup can only have system [no device, no sensor]
5.GRoup can have only sensor[no system, no device]
so please give me query for this. not stored procedures.i need query for this

View 3 Replies View Related

Logic For A Complex Function&&amp; Which Tasks To Use

May 28, 2008



Input Columns

Jan,Feb,March,April,May,June,July......December

All these columns Have Boolean 'Y' Or 'N' Data

Here is what i want as output

Example

Jan 'Y'
Feb 'Y'
March'Y'
April'Y'
May 'N'
June 'Y'
July 'Y'
..
..
..
Dec 'Y'

Output should be:

Start date:jan/year
End date:April/year
Again the start date:May/year
End Date: dec/year

So basically For the same person i should have two recods...

Text file to sql server 2005

How can i achieve this
Please let me know

View 14 Replies View Related

Finding A Change Complex Logic..

Apr 25, 2008



I have records like below

ID Facility Procedure Date Action

1001 A 888 07/01/2007

1002 A 888 07/31/2007

1003 B 888 09/01/2007
1004 B 888 09/15/2007

1005 B 888 10/11/2007

1006 B 999 10/24/2007
1007 B 777 10/25/2007
1008 B 777 10/30/2007



I have to update an action column based on the business logic below.

1. if there is a change in FACILITY with the same PROCEDURE and the DATE between new facility and the date of previous record is less than 30 days ,

then update ACTION = TP

2. if there is a change in procedure , update Action = TS

3. is there is a change in FACILITY but have different PROCEDURE, then NO UPDATE



The output should look like below:

ID 1003 has TP because the FACILITY has changed with the same PROCEDURE compare to the previous record and the DATE is less than 30 days

ID 1006 has TS because the PROCEDURE has changed compare to previous record

ID 1009 didn€™t get changed because it has different PROCEDURE even though FACILITY got changed...

ID Facility Procedure Date Action

1001 A 888 07/01/2007

1002 A 888 07/31/2007

1003 B 888 08/05/2007 TP

1004 B 888 09/15/2007

1005 B 888 10/11/2007

1006 B 999 10/24/2007 TS

1007 B 999 10/25/2007

1008 B 777 10/30/2007 TS

1009 D 666 11/07/2007


What is the best way to do this? Do I have to use a cursor to compare each record? Can you sow me some code examples?

View 2 Replies View Related

Complex Row Level Security Logic In SecurityFilter

Oct 8, 2007

Hi, I am trying to replicate the row level security rules in reporting service and realize the "security filter" property is a pure client side filter expression.

In our old system, we are using a set of rules to decide the row level security, something like:

if user is owner of this file or
( if user's department matches this file and the user is the department manager ) or
if this user has unfinished task associated with this file or
...

So obviously it need more information than the just GetUserId(). What we have done is creating a CLR UDF as GetUserCaseList( int uid ) and returns a two column table ( case_id, case_right ).

We want to somehow inject these logics into the reporting while the user is using reportBuilder.exe, but we cannot find a way to put it into the data source view and/or the semantic data model.

I am pretty sure I am not the only guy who's having this problem, but I cannot find any hint....

Thanks in advance.

Jian

View 3 Replies View Related

Is There Any Easy Way To Evaluate Complex Date Logic In Expressions?

Dec 7, 2006

Hello all,

I am new to SSIS, so I am hoping there is an easier way to do this...

I need to evaluate a date in a field and determine if it is between the beginning and end of whatever the current month is...  In Access, this was written as something like:

 

IIF(datevalue >= CDate(Format(Now(),"mm/01/yy")) AND datevalue < CDate(Format(DateAdd("m",1,Now()), "mm/01/yy)), value1, value2)

 

Trying to recreate this in SSIS using expressions during a derived transformation has been extremely difficult.  Here is what I came up with:

 (DUE_DATE >= (DT_DATE)( (DT_WSTR,2)MONTH(GETDATE())+"/01/"+ (DT_WSTR,2)YEAR(GETDATE()))) && (DUE_DATE<(DT_DATE)( (DT_WSTR,2)MONTH( DATEADD("m",1,GETDATE()) )+"/01/"+(DT_WSTR,2)YEAR( DATEADD("m",1,GETDATE() )))) ? value1 : value2



 

Any help you all could give would be appreciated.

 

Thanks!

 

Josh

View 7 Replies View Related

Update Trigger Logic

Nov 8, 2004

Posts: 20
Joined: Aug 2003
Mon November 08, 2004 9:42 AM



I have a table where from 1 to 3 fields will be update (lastname,firstname,birthdate). Any combination of the 3 can be updated. I need a trigger to handle the updates which update some other db tables. I can handle the update trigger part, the ? is how to best approach the logic. I can do thee separate statements to handle an update for each of the columns, but that could cause 3 separate updates to fire. I was looking at doing something like

If UPDATE(last_name)
and UPDATE(first_name)
and update(date_of_birth)
BEGIN
...
end
else if
If UPDATE(last_name)
and UPDATE(first_name)
begin
...
end

View 1 Replies View Related

Logic On UPDATE Query

Jan 25, 2006

I am dealing with two tables and I am trying to take one column from a table and match the records with another table and append the data of that column.

I used an update query that looks like this:

UPDATE Acct_table Set Acct_table.Score =
(Select Score_tbl.Score from Score_tbl
Where Acct_table.Acctnb = Score_tbl.Acctnb

This process has been running for over an hour and a half and is building a large log file. I am curious to know if there is a better command that I can use in order to join the tables and then just drop the column from one to the other. Both tables are indexed on Acctnb.

Any insight would truly help.
Thanks!

View 4 Replies View Related

Update Logic In Warehouse ...

Feb 5, 2008

Hi,

I am facing a small problem while updating the warehouse using SSIS package.

Here is an sample scenario.
I have a staging table T1 with some important columns as stateid,ename etc ..
and target table as Trg with only two columns stateid and statecnt.
The Rule is, each state will be sending an excel file which basically contains state and employees belonging to the state information.
For the first time when i execute the SSIS package, i need to load statetid and count_of_employees for that particular state.
say for example.

SELECT stateid,
count(ename)
from T1
where stateid = ?

For the next time if the same state information is received then we need to update the count to the existing record in the Dataware house rather than creating a brand new record once again.

I am little bit confused of implementig this logic.
Can anyone help me out in accomplishing this task.
What can done or what steps is involved in achiving the task.

Thanks in advance.

View 2 Replies View Related

Update Statement Logic

May 9, 2008

Hi guys

We have a table X with a gender column taking values M(male) or F(Female).There are 52 rows in the table X.We want to update all the rows with Gender M as F and update all remaining F as males (M) in a single Update Query.Im looking for the exact logic we would write in the single update statement.
Please help me out.

Thanks in advance

Regards
ARvind L

View 2 Replies View Related

Implement Logic For Update Or Insert

May 1, 2006

I have a stored procedure that I need to either perform an update if a record exists or an insert if the record doesn't exist.

Here is my procedure:

CREATE PROCEDURE dbo.Insert_Temp_ContactInfo

@sessionid varchar(50),
@FirstName varchar(50),
@LastName varchar(50),
@SchoolName varchar(50),
@address varchar(50),
@City varchar(50),
@State int,
@Zip varchar(5),
@Phone varchar(10),
@Email varchar(50),
@CurrentCustomer varchar(3),
@ImplementationType int,
@ProductType int = null,
@Comment varchar(500)

AS

--check if a current record exists

SET NOCOUNT ON

SELECT FirstName, LastName, SchoolName, Address, City, State, Zip, Phone, Email, CurrentCustomer, ImplementationType, ProductType, Comment
FROM dbo.Temp_ContactInfo
WHERE sessionid = @sessionid


SET NOCOUNT OFF


--if exists update the record

UPDATE dbo.Temp_ContactInfo
SET
FirstName = @FirstName,
LastName = @LastName,
SchoolName = @SchoolName,
Address = @address,
City = @City,
State = @State,
Zip = @Zip,
Phone = @Phone,
Email = @Email,
CurrentCustomer = @CurrentCustomer,
ImplementationType = @ImplementationType,
ProductType = @ProductType,
Comment = @Comment
WHERE sessionid = @sessionid

--if the record does not exist, then insert a new record

INSERT INTO dbo.Temp_ContactInfo (sessionid, FirstName, LastName, SchoolName, address, City, State, Zip, Phone, Email, CurrentCustomer, ImplementationType, ProductType, Comment)
VALUES (@sessionid, @FirstName, @LastName, @SchoolName, @address, @City, @State, @Zip, @Phone, @Email, @CurrentCustomer, @ImplementationType, @ProductType, @Comment)

GO

I think I can use an if statement. Can anyone help me out with this?

Thanks.

View 3 Replies View Related

Log Explorer Vs. ApexSQL Log Vs. SQL Log-Rescue

Jun 8, 2006

Opinions?I've installed all three to try'em out and they all seem to be workingso far, more or less.Log Explorer has given me a couple of errors but I started over andcontinued OK.ApexSQL Log squawked about "redo for delete cannot be generated fortables lacking clustered index". Huh? What the...? We have lots oftables without a clustered index.I read some reports in Red-Gate's technical support forum about theirproduct actually bringing down SQL Server. That did not inspireconfidence.All three install some server-side components like extended storedproc's which I'm not crazy about and I think all three are server orinstance licensed (does anyone actually purchase more than one licensewhen it seems like you can easily move any tran log to be analyzed tothe server the product is installed on?). I don't think I'd want toinstall any of them on a Production server, at least one that I'mresponsible for!Thanks,Martin

View 1 Replies View Related

How I Rescue Data From Corrupted Databases

Mar 7, 2007

Edit: Some changes added

This is my procedure for "rescuing" data from a corrupted database. Obviously restoring from backup is a lot easier!

0) Set the damaged database to Read-Only. if you don't have a backup make one now.

1) Script the database

2a) Create a new, TEMP database - preferably on a different machine in case of hardware problems on the original machine

2b) Size the Data for the TEMP database same size as the original (to avoid dynamic extensions). Size the Log something large-ish!

3) Run the Script on the TEMP database. Do NOT create any FK etc. yet

4a) Attempt to transfer all tables:

-- Prepare script of: INSERT INTO ... SELECT * FROM ...
SET NOCOUNT ON
SELECT 'PRINT ''' + name + '''' + CHAR(13) + CHAR(10) + 'GO' + CHAR(13) + CHAR(10)
+ CASE WHEN C.id IS NULL
THEN ''
ELSE 'SET IDENTITY_INSERT dbo.[' + name + '] ON' + CHAR(13) + CHAR(10)
END
+ 'INSERT INTO MyTempDatabase.dbo.[' + name + ']' + CHAR(13) + CHAR(10)
+ 'SELECT * FROM dbo.[' + name + ']' + CHAR(13) + CHAR(10)
+ CASE WHEN C.id IS NULL
THEN ''
ELSE 'SET IDENTITY_INSERT dbo.[' + name + '] OFF' + CHAR(13) + CHAR(10)
END
+ 'GO'
FROMdbo.sysobjects AS O
LEFT OUTER JOIN
(
SELECT DISTINCT C.id
FROMdbo.syscolumns AS C
WHEREC.colstat = 1-- Identity column
) AS C
ON C.id = O.id
WHERE type = 'U'
AND name NOT IN ('dtproperties')
ORDER BY name
SET NOCOUNT OFF

this generates statements like this:

PRINT 'MyTable'
GO
SET IDENTITY_INSERT dbo.[MyTable] ON
INSERT INTO RESTORE_XFER_TEMP.dbo.[MyTable]
SELECT * FROM dbo.[MyTable]
SET IDENTITY_INSERT dbo.[MyTable] OFF
GO

4b) This will give some sort of error on the tables which cannot be copied, and they will need to be rescued by some other means.

5a) Each "broken" table needs to be rescued using an index. Ideally you will have a clustered index on the PK and that will be undamaged, so you can "rescue" all the PKs into a temp table:

-- Copy PK fields to a temporary table
-- DROP TABLE MyRestoreDatabase.dbo.TEMP_RESCUE_PK
-- TRUNCATE TABLE MyRestoreDatabase.dbo.MyBrokenTable
SELECT[ID]=IDENTITY(int, 1, 1),
[IsCopied]=CONVERT(tinyint, 0),
MyPK
INTOMyRestoreDatabase.dbo.TEMP_RESCUE_PK
FROMMyBrokenDatabase.dbo.MyBrokenTable
ORDER BY MyPK

5b) If that is successful you have a list of all the PKs, so can can try to copy data matching those PKs, in batches:

-- If OK then selectively copy data across
-- First Prep. a temp Batch table
-- DROP TABLE MyRestoreDatabase.dbo.TEMP_RESCUE_BATCH
SELECT TOP 1 [ID]=CONVERT(int, NULL), [IsCopied]=CONVERT(bit, 0), MyPK
INTOMyRestoreDatabase.dbo.TEMP_RESCUE_BATCH
FROMMyRestoreDatabase.dbo.TEMP_RESCUE_PK
GO
--
DECLARE@intStartint,
@intStopint,
@intBatchSizeint

-- NOTE: After the first run set these to any "gaps" in the table that you want to fill
SELECT
@intStart = 1,
@intBatchSize = 10000,
@intStop = (SELECT MAX([ID]) FROM MyRestoreDatabase.dbo.TEMP_RESCUE_PK)

SELECT@intStart = MIN([ID])
FROMMyRestoreDatabase.dbo.TEMP_RESCUE_PK
WHERE IsCopied = 0
AND [ID] >= @intStart

WHILE@intStart < @intStop
BEGIN
SET ROWCOUNT @intBatchSize

-- Isolate batch of Keys into separate table
TRUNCATE TABLE MyRestoreDatabase.dbo.TEMP_RESCUE_BATCH
INSERT INTO MyRestoreDatabase.dbo.TEMP_RESCUE_BATCH
SELECTT.*
FROMMyRestoreDatabase.dbo.TEMP_RESCUE_PK AS T
WHERE IsCopied = 0
AND [ID] >= @intStart
AND [ID] < @intStart + @intBatchSize

-- Attempt to copy matching records, for this batch
PRINT CONVERT(varchar(20), @intStart)
INSERT INTO MyRestoreDatabase.dbo.MyBrokenTable
SELECTS.*
FROMMyRestoreDatabase.dbo.TEMP_RESCUE_BATCH AS T
LEFT OUTER JOIN MyRestoreDatabase.dbo.MyBrokenTable AS D
ON D.MyPK = T.MyPK
-- This will try to get the data from the broken table, it may fail!
JOIN MyBrokenDatabase.dbo.MyBrokenTable AS S
ON S.MyPK = T.MyPK
WHERED.MyPK IS NULL-- Belt and braces so as not to copy existing rows

-- Flag the rows just "Copied"
UPDATEU
SETIsCopied = 1
FROMMyRestoreDatabase.dbo.TEMP_RESCUE_PK AS U
WHEREIsCopied = 0
AND [ID] >= @intStart
AND [ID] < @intStart + @intBatchSize

-- Loop round, until done
SELECT@intStart = @intStart + @intBatchSize
END
GO
SET ROWCOUNT 0-- Turn OFF!!
GO

5c) This will copy in batches of 10,000 [you can adjust @intbatchSize depending on table size] until it gets to a damaged part of the table, then it will abort.

Change the @intStart to the last ID number displayed, and reduce @intBatchSize (by an order of magnitude each time) until you have rescued as many records as possible in the first "part" of the table.

5d) Reset the batch size @intBatchSize to 10,000 [or whatever size is appropriate], and increase the @intStart repeatedly until you are past the damaged section - copying will start again, and will abort if there are further damaged sections

5e) Repeat that process until you have rescued as much of the data as is possible

6) Check what is left to be rescued

-- Check amount NOT done:
SELECTCOUNT(*), MIN([ID]), MAX([ID])
FROMMyRestoreDatabase.dbo.TEMP_RESCUE_PK
WHERE IsCopied = 0
--AND [ID] > 123456-- Optionally count items after a "gap"
--
-- Double check that IsCopied set correctly, and the number of records "lost"
SELECTCOUNT(*),
[IsCopied] = SUM(CONVERT(int, IsCopied)),
[IsCopied+Record] = SUM(CASE WHEN IsCopied = 1 AND C.MyPK IS NOT NULL THEN 1 ELSE 0 END),
[IsCopiedNoRecord] = SUM(CASE WHEN IsCopied = 1 AND C.MyPK IS NULL THEN 1 ELSE 0 END),
[IsNOTCopied] = SUM(CASE WHEN IsCopied = 0THEN 1 ELSE 0 END),
[IsNOTCopied+Record] = SUM(CASE WHEN IsCopied = 0 AND C.MyPK IS NOT NULL THEN 1 ELSE 0 END),
[IsNOTCopiedNoRecord] = SUM(CASE WHEN IsCopied = 0 AND C.MyPK IS NULL THEN 1 ELSE 0 END)
FROMMyRestoreDatabase.dbo.TEMP_RESCUE_PK AS T
LEFT OUTER JOIN MyRestoreDatabase.dbo.MyBrokenTable AS C
ON C.MyPK = T.MyPK
--
-- List of "Lost" records
SELECTMyPK
FROMMyRestoreDatabase.dbo.TEMP_RESCUE_PK
WHERE IsCopied = 0
ORDER BY [ID]

You will then have to "find" and rescue the lost records somewhere.

I have a further process using OPENQUERY() to rescue records to fill the gaps in the event that they are available on a remote system - a straight JOIN to get them is going to be far to slow on anything other than tiny tables!

7a) Create the FKs etc. Update the statistics, rebuild indexes, and possibly shrink the Log if it is unrealistically big
7b) Backup and Restore over the original database
7c) DBCC CHECKDB ('MyDatabaseName') WITH ALL_ERRORMSGS, NO_INFOMSGS

Good luck!

Kristen

View 4 Replies View Related

Merge Replication – Bug In Business Logic Update Handler

Nov 17, 2006

I have got a business logic update conflict handler working, but I have had to work round what appears to be a bug.

Please can someone confirm if this is indeed a bug €“ and if it is a known bug?

My conflict handler needs to take some columns from the publisher row and some from the subscriber row in the event of conflict.

I can quite happily generate a custom dataset which contains the winning row that I want €“ I can see that because I can step through the conflict handler with debug when a conflict occurs.

However, just returning ActionOnUpdateConflict.AcceptCustomConflictData from the UpdateConflictsHandler method does not set the publisher and subscriber columns correctly. I end up with different values on the two databases.

I have found that the only way to get the correct rows on both publisher and subscriber is to create a new ADO connection to the publisher and actually perform an update €“ updating all the modified columns. This now works reliably in my testing.

Fortunately, due to business rules the frequency of update conflicts are likely to be very infrequent, but I would very much like to avoid having to do the €˜unnecessary€™ update.

Notes:

I am using column level tracking €“ but I have seen the problem with row level tracking too
I have mainly been using SP1 but have repeated the test on a configuration using the SP2 CTP €“ and the problem occurs there too
The problem is not due to complex logic in my code. If the method just sets customDataSet = publisherDataSet.Copy and then returns ActionOnUpdateConflict.AcceptCustomConflictData, the changed and winning publisher values are not sent to the subscriber

Any thoughts would be much appreciated

View 5 Replies View Related

Help With A Complex UPDATE Query

Nov 18, 2006

Well, I think it's complex anyway -- you might not :)TableDef:CREATE TABLE CustTransactions (TransactionKey int IDENTITY(1,1) NOT NULL,CustomerID int,AmountSpent float,CustSelected bit default 0);TransactionKey is the primary key, CustomerID and AmountSpent are bothindexed (non unique).What I would like to do is, for all of the records in descending orderof "AmountSpent" where "CustSelected = TRUE", set CustSelected to FALSEsuch that the sum of all the AmountSpent records with CustSelected =TRUE is no greater than a specified amount (say $50,000).What I'm doing at the moment is a "SELECT * FROM CustTransactions WHERECustSelected = TRUE ORDER BY AmountSpent;", programatically loopingthrough all the records until AmountSpent 50000, then continuine toloop through the remainder of the records setting CustSelected = FALSE.This does exactly what I want but is slow and inefficient. I am sure itcould be done in a single SQL statement with subqueries, but I lack theknowledge and experience to figure out how.The closest I can get is:-UPDATE CustTransactions SET CustSelected = FALSEWHERE (CustSelected = TRUE)AND TransactionKey NOT IN(SELECT TOP 50000 TransactionKey FROM CustTransactions WHERE(((CustTransactions.CustSelected)=TRUE))ORDER BY AmountSpect DESC, TransactionKey ASC);However, this mereley ensures only the top 50,000 customers by amountspent remain "selected", not the top "X" customers whose total spendis $50,000. I really need to replace the "SELECT TOP 50000" with someform of "SELECT TOP (X rows until sum(AmountSpent) =50000)".Is it even possible to achieve what I'm trying to do?Thanks in advance for any assistance offered!--SlowerThanYou

View 13 Replies View Related

Please HELP Complex Update Need Genius

Apr 6, 2008

please HELP complex update need genius
the table before the UPDATE





f555
f55
f5
f444
f44
f4
f333
f33
f3
f22
f22
f2
f11
f11
f1
fname
val
id
















aaaa
2
1234



2


4


3


1


2
aaaa
1
1234
















bbbb
2
9998



z


x


4


z


1
bbbb
1
9998
















cccc
2
4321



1


1


1


1


1
cccc
1
4321
















dddd
2
9876



w


2


2


k


2
dddd
1
9876

the table after the UPDATE
(i need to update BY the ID of the Employee)
i need to update only the numbers
if the value =1 then the upper fields =aa ab ac
if the value =2 then the upper fields =ba bb bc
if the value =3 then the upper fields =ca cb cc
if the value =4 then the upper fields =da db dc
evry employee have 2 ROWS
val 1 and val 2
and the table i ORDER BY ID,fname,val




f555
f55
f5
f444
f44
f4
f333
f33
f3
f22
f22
f2
f11
f11
f1
fname
val
id

bc
bb
ba
dc
db
da
cc
cb
ca
ac
ab
aa
bc
bb
ba
aaaa
2
1234



2


4


3


1


2
aaaa
1
1234







dc
db
da



ac
ab
aa
bbbb
2
9998



z


x


4


z


1
bbbb
1
9998

ac
ab
aa
ac
ab
aa
ac
ab
aa
ac
ab
aa
ac
ab
aa
cccc
2
4321



1


1


1


1


1
cccc
1
4321




bc
bb
ba
bc
bb
ba



bc
bb
ba
dddd
2
9876



w


2


2


k


2
dddd
1
9876


i am appraiser the help
TNX

View 16 Replies View Related

Complex Update Statement Not Working

Nov 6, 2006

hi.

can somebody explain to me why the below
update fails to update one row and updates
the entire table?


Code:


UPDATE addlist
SET add_s = 1
WHERE EXISTS
(SELECT a.add_s, a.email_address, e.public_name
FROM add a, edit e
WHERE a.email_address = e.email_address
and a.add_email = 'mags23@rice.edu' and a.add_s = 0 and e.public_name = 'professor');



and, what is the solution? thank you.

View 8 Replies View Related

SQL Server 2012 :: Replacing CASE Statement In Update With Table-driven Logic

Oct 20, 2014

I have a stored proc that contains an update which utilizes a case statement to populate values in a particular column in a table, based on values found in other columns within the same table. The existing update looks like this (object names and values have been changed to protect the innocent):

UPDATE dbo.target_table
set target_column =
case
when source_column_1= 'ABC'then 'XYZ'
when source_column_2= '123'then 'PDQ'

[Code] ....

The powers that be would like to replace this case statement with some sort of table-driven structure, so that the mapping rules defined above can be maintained in the database by the business owner, rather than having it embedded in code and thus requiring developer intervention to perform changes/additions to the rules.

The rules defined in the case statement are in a pre-defined sequence which reflects the order of precedence in which the rules are to be applied (in other words, if a matching value in source_column_1 is found, this trumps a conflicting matching value in source_column_2, etc). A case statement handles this nicely, of course, because the case statement will stop when it finds the first "hit" amongst the WHEN clauses, testing each in the order in which they are coded in the proc logic.

What I'm struggling with is how to replicate this using a lookup table of some sort and joins from the target table to the lookup to replace the above case statement. I'm thinking that I would need a lookup table that has column name/value pairings, with a sequence number on each row that designates the row's placement in the precedence hierarchy. I'd then join to the lookup table somehow based on column names and values and return the match with the lowest sequence number, or something to that effect.

View 9 Replies View Related

Data Access :: Bulk Fetch Records And Insert / Update Same In Other Table With Some Business Logic

Apr 21, 2015

I am currently working with C and SQL Server 2012. My requirement is to Bulk fetch the records and Insert/Update the same in the other table with some  business logic? How do i do this?

View 14 Replies View Related

Complex DB Search Forms (Store Proc Vs. Complex Where)

Nov 12, 2003

I have web forms with about 10-15 optional search parameters (fields) for a give table. Each item (textbox) in the form is treated as an AND condition.

Right now I build complex WHERE clauses based on wheather data is present in a textbox and AND each one in the clause. Also, if a particular field is "match any word", i get a ANDed set of OR's. As you can imagine, the WHERE clause gets quite large.

I build clauses like this (i.e., 4 fields shown):

SELECT * from tableName WHERE (aaa like '%data') AND (bbb = 'data') AND (ccc like 'data%') AND ( (xxx like '%data') OR (yyy like '%data%') )

My question is, are stored procedures better for building such dynamic SQL clauses? I may have one field or all fifteen. I've written generic code for building the clauses, but I don't know much about stored procedures and am wondering if I'm making this more difficult on myself.

View 7 Replies View Related

How To Swap A Row Of Data With Another

Jun 27, 2006

Hi,

I'm pretty new to SQL and certainly new to SQL Server, so this is no doubt a simple question, but how can I take a row of data (say row 117) and swap it with another specified row of data? I know it sounds odd, but the key for each row is automatically generated so I don't want to mess with that, so I just want to swap the other fields.

Here's an example of what I mean:

----------------------------------------------
ID | headline | content | newstype | date |
----------------------------------------------
117 | test | asdfgasd| industry | 06/06|
118 | test2 | adsfg as| company | 06/06|
----------------------------------------------

What i've discovered is that the order of data in the rows isn't correct, so I want to maintain the ID fields seeing as they're in numeric order, but then use that ID to grab the rest of the row (117 for example) and replace the data for 118 with 117's data. Then do the same with 118's original data....

I need to do this because all the related rows in my table were posted on the same date, so other than that they appear on screen based on where they appear in the table, which doesn't match what the client wants...

Sorry for the long post, but as a beginner with SQL I wanted to make sure I made sense!

View 6 Replies View Related

How Can I Swap Two Rows In A Table

May 19, 2005

I need to swap two rows in a table so that i can give the user a choice to move the row data up and down. The top and bottom row values may not be in the serial order. I am using MS Sql 2000. Is there any way to do that or its really difficult big process. I really stuck with this problem can you help me out, please friends.. Your help will greatly appreciated..
Thank you very much

View 3 Replies View Related

Swap Database To A New Server

Feb 3, 2008

hi, we have got a new server at work running SBS 2003. the old server was SBS 2000 and it has a database on it. Both are running the SQL server program. Can anyone give me instructions to transfer these over (i have no idea how). i realise this has probably been asked before but i dont have the time to search so if someone could link a thread with instructions that would be good. cheers.

View 2 Replies View Related

Challenge - Swap Two Columns

Apr 30, 2004

Ok .. a challenge ...

How do you swap two columns based on some condition without using a cursor ( I mean a set based solution).

View 12 Replies View Related

Swap Column Position

Jul 20, 2005

What is a good method/mechanism to swap the position of multiplecolumns?For instance, tblXZY has the followings columns and respectivepositions:tblXZY======xyzUUID 1fn 2ln 3phone 4email 5city 6state 7....Now, I need to make city as 2 and state as 3. BTW, the tblXYZ tablehas data there. Copy/select all the data into a new table withdesired column position would require constraints re-mapping etc.,which seems quite a bit hassle.Thanks.

View 6 Replies View Related

Log Shipping- How To Resume After Swap

Oct 30, 2006

I have setup logshipping in sql 2005. i have a primary and secondary server only.
Suppose for maintenace i bring primary down. . i have to manually bring the secondary server online. usnig restore databse with restore.

1) so far so good. But what now. How can i re-sync the old primary with the new primary?

2) can i return the original secondary back to standby mode so that the primary can resume its role and the log shipping process proceeds.

View 5 Replies View Related

Swap Rows For Columns In A Table

May 12, 2008

have the following table:


RecordKey MonthYear SD1 SD2 SD3
1 Jan 2008 6 AA 0
2 Feb 2008 10 BB 3
3 Mar 2008 12 CC 8

etc....



I need to transform it to this:


1 2 3

Jan 2008 Feb 2008 Mar 2008
6 10 12
AA BB CC
0 3 8



Can this be done automatically in SQL?

View 3 Replies View Related

Swap The Data Between 2 Columns Of A Table In Sql

Sep 24, 2007

I have a table named tbOrders. I want to swap the data between 2 of its columns named OrderNumber and CaseNumber.

Both the columns are varchar datatype. How can i swap the data between the two columns?

View 5 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved