Showing posts with label update. Show all posts
Showing posts with label update. Show all posts

Tuesday, March 27, 2012

case statement

How do i update a column using case statement.

I have a column that has values from 1 to 5.

I wanna update it like: case 1 then change the value to xyz

case 2 then change the value to abc

can anyone help me with the script?

thanks

Not sure whether you are looking for sql command to do this or looking to do this in SSIS ? The sql command to do this would be something like this:

update Table

set column = case when column = 1 then xyz

when column = 2 then abc

end

In SSIS, you can use an execute sql task with a similar command as above.

|||Thanks. this is what i need. i was using the case statement incorrectly.sql

Thursday, March 22, 2012

CASE Question

Hi,

I’ve got an update like this one:

UPDATE PROCESSOS

SET

CDU_TIPOSERVICO =

CASE

WHEN CDU_TIPOSERVICO = 'CSS'THEN CDU_TIPOSERVICO

WHEN CDU_TIPOSERVICO = 'USP'THEN ‘FFF’

WHEN CDU_TIPOSERVICO = 'PES'

ELSE ‘XXX’

END

On the first “when” if the variable is equal to ‘CSS’ I want to do nothing, I mean I want the variable to keep its value, how can I achieve that ?

Should I do -> WHEN CDU_TIPOSERVICO = 'CSS'THEN CDU_TIPOSERVICO

Or, there is another way ?

Thanks !

Your logic is perfectly correct...

Other possible solution - don't run the update statement against the 'CSS',

Code Block

update processos

set

cdu_tiposervico =

case

when cdu_tiposervico = 'USP' then 'fff'

when cdu_tiposervico = 'PES' then 'some value'

else ‘xxx’

end

where

isnull(cdu_tiposervico,'') <> 'CSS'

|||

Hi.

Thanks for your reply.

I didn't understood this part - isnull(cdu_tiposervico,'') <> 'CSS'

why not just where cdu_tiposervico <>'CSS'

What the functionality of the second parameter in the function isnull ?

|||

If there is any null value on "cdu_tiposervico" then the corresponding "cdu_tiposervico" will be updated with 'XXX'.

If you reomove isnull the null value will be retained as NULL.

Tuesday, March 20, 2012

Case in a Where clause

Hi all,
I have the following sql statement (it's ugly and it's not my work!!!).
UPDATE abo_tags SET locked = @.PrimaryGroupFilter, locking_user = @.user,
lockingdate = @.sDate
FROM abo_tags
INNER JOIN abo ON abo_tags.id_no_abo = abo.id_no
INNER JOIN products ON abo.id_no_product = products.id_no
LEFT OUTER JOIN abo_tags_subsidies ON abo_tags.id_no =
abo_tags_subsidies.id_no_abo_tag
WHERE abo_tags.id_no_invoice_type = 2 and abo_tags.locked in ('0', '',
NULL)
and abo_tags.validity_date >= @.mdatInvoiceFrom
and abo_tags.validity_date <= @.mdatInvoiceTo
and abo.id_no_primarygroup in (select primchild from invoicehelp where
parentkey = @.PrimaryGroupFilter)
and abo.id_no_product = case when @.mlngProduct >0 then @.mlngProduct else
abo.id_no_product end
and abo.id_no_school = case when @.mlngSchool > 0 then @.mlngSchool else
abo.id_no_school end
and abo_tags_subsidies.id_no_costrepresentative = case when @.mlngCostRep>0
then @.mlngCostRep else abo_tags_subsidies.id_no_costrepresentative end
I noticed that it takes a while to update records (over 20sec) on a table on
500K records. It looks like the problem lies in the CASE statements in the
WHERE clause. Is there a way to do it better than this?
Thanks,
IvanIvan,
Supposing that are int datatype, then try:
WHERE
abo_tags.id_no_invoice_type = 2 and abo_tags.locked in ('0', '')
and abo_tags.validity_date >= @.mdatInvoiceFrom
and abo_tags.validity_date <= @.mdatInvoiceTo
and abo.id_no_primarygroup in (
select primchild
from invoicehelp
where
parentkey = @.PrimaryGroupFilter)
and abo.id_no_product between coalesce(nullif(@.mlngProduct, 0), 1) and
coalesce(nullif(@.mlngProduct, 0), 2147483647)
and abo.id_no_school between coalesce(nullif(@.mlngSchool, 0), 1) and
coalesce(nullif(@.mlngSchool, 0), 2147483647)
and abo_tags_subsidies.id_no_costrepresentative between
coalesce(nullif(@.mlngCostRep, 0), 1) and coalesce(nullif(@.mlngCostRep, 0),
2147483647)
)
also, take off the null value from the list used with first IN operator.

> abo_tags.id_no_invoice_type = 2 and abo_tags.locked in ('0', '', null)
abo_tags.id_no_invoice_type = 2 and abo_tags.locked in ('0', '')
Dynamic Search Conditions in T-SQL
http://www.sommarskog.se/dyn-search.html
AMB
"Ivan Debono" wrote:

> Hi all,
> I have the following sql statement (it's ugly and it's not my work!!!).
> UPDATE abo_tags SET locked = @.PrimaryGroupFilter, locking_user = @.user,
> lockingdate = @.sDate
> FROM abo_tags
> INNER JOIN abo ON abo_tags.id_no_abo = abo.id_no
> INNER JOIN products ON abo.id_no_product = products.id_no
> LEFT OUTER JOIN abo_tags_subsidies ON abo_tags.id_no =
> abo_tags_subsidies.id_no_abo_tag
> WHERE abo_tags.id_no_invoice_type = 2 and abo_tags.locked in ('0', '',
> NULL)
> and abo_tags.validity_date >= @.mdatInvoiceFrom
> and abo_tags.validity_date <= @.mdatInvoiceTo
> and abo.id_no_primarygroup in (select primchild from invoicehelp where
> parentkey = @.PrimaryGroupFilter)
> and abo.id_no_product = case when @.mlngProduct >0 then @.mlngProduct else
> abo.id_no_product end
> and abo.id_no_school = case when @.mlngSchool > 0 then @.mlngSchool else
> abo.id_no_school end
> and abo_tags_subsidies.id_no_costrepresentative = case when @.mlngCostRep>
0
> then @.mlngCostRep else abo_tags_subsidies.id_no_costrepresentative end
> I noticed that it takes a while to update records (over 20sec) on a table
on
> 500K records. It looks like the problem lies in the CASE statements in the
> WHERE clause. Is there a way to do it better than this?
> Thanks,
> Ivan
>
>|||hi Ivan
This is the equivalent after removing the CASE in Where Clause:
UPDATE abo_tags
SET locked = @.PrimaryGroupFilter,
locking_user = @.user,
lockingdate = @.sDate
FROM abo_tags
INNER JOIN abo ON abo_tags.id_no_abo = abo.id_no
INNER JOIN products ON abo.id_no_product = products.id_no
LEFT OUTER JOIN abo_tags_subsidies ON abo_tags.id_no =
abo_tags_subsidies.id_no_abo_tag
WHERE
abo_tags.id_no_invoice_type = 2 and abo_tags.locked in ('0', '',NULL)
and abo_tags.validity_date >= @.mdatInvoiceFrom
and abo_tags.validity_date <= @.mdatInvoiceTo
and abo.id_no_primarygroup in (select primchild from invoicehelp where
parentkey = @.PrimaryGroupFilter)
and ((@.mlngProduct > 0 AND abo.id_no_product=@.mlngProduct) OR (@.mlngProduct
<= 0))
and ((@.mlngSchool > 0 AND abo.id_no_school=@.mlngSchool) OR (@.mlngSchool <= 0
))
and ((@.mlngCostRep > 0 AND abo_tags_subsidies.id_no_costrepresentative =
@.mlngCostRep) OR (@.mlngCostRep <= 0) )
I dont thin, there is a problem with the CASE. I believe its because of the
in (select primchild from invoicehelp where
parentkey = @.PrimaryGroupFilter)
please let me if this answers your question.
best Regards,
Chandra
http://chanduas.blogspot.com/
http://groups.msn.com/SQLResource/
---
"Ivan Debono" wrote:

> Hi all,
> I have the following sql statement (it's ugly and it's not my work!!!).
> UPDATE abo_tags SET locked = @.PrimaryGroupFilter, locking_user = @.user,
> lockingdate = @.sDate
> FROM abo_tags
> INNER JOIN abo ON abo_tags.id_no_abo = abo.id_no
> INNER JOIN products ON abo.id_no_product = products.id_no
> LEFT OUTER JOIN abo_tags_subsidies ON abo_tags.id_no =
> abo_tags_subsidies.id_no_abo_tag
> WHERE abo_tags.id_no_invoice_type = 2 and abo_tags.locked in ('0', '',
> NULL)
> and abo_tags.validity_date >= @.mdatInvoiceFrom
> and abo_tags.validity_date <= @.mdatInvoiceTo
> and abo.id_no_primarygroup in (select primchild from invoicehelp where
> parentkey = @.PrimaryGroupFilter)
> and abo.id_no_product = case when @.mlngProduct >0 then @.mlngProduct else
> abo.id_no_product end
> and abo.id_no_school = case when @.mlngSchool > 0 then @.mlngSchool else
> abo.id_no_school end
> and abo_tags_subsidies.id_no_costrepresentative = case when @.mlngCostRep>
0
> then @.mlngCostRep else abo_tags_subsidies.id_no_costrepresentative end
> I noticed that it takes a while to update records (over 20sec) on a table
on
> 500K records. It looks like the problem lies in the CASE statements in the
> WHERE clause. Is there a way to do it better than this?
> Thanks,
> Ivan
>
>|||Hi
Here is the query after removing the IN
UPDATE abo_tags
SET locked = @.PrimaryGroupFilter,
locking_user = @.user,
lockingdate = @.sDate
FROM abo_tags
INNER JOIN abo ON abo_tags.id_no_abo = abo.id_no
INNER JOIN products ON abo.id_no_product = products.id_no
INNER JOIN invoicehelp ON primchild = abo.id_no_primarygroup
LEFT OUTER JOIN abo_tags_subsidies ON abo_tags.id_no =
abo_tags_subsidies.id_no_abo_tag
WHERE
abo_tags.id_no_invoice_type = 2 and abo_tags.locked in ('0', '',NULL)
and abo_tags.validity_date >= @.mdatInvoiceFrom
and abo_tags.validity_date <= @.mdatInvoiceTo
and invoicehelp.parentkey = @.PrimaryGroupFilter
and ((@.mlngProduct > 0 AND abo.id_no_product=@.mlngProduct) OR (@.mlngProduct
<= 0))
and ((@.mlngSchool > 0 AND abo.id_no_school=@.mlngSchool) OR (@.mlngSchool <= 0
))
and ((@.mlngCostRep > 0 AND abo_tags_subsidies.id_no_costrepresentative =
@.mlngCostRep) OR (@.mlngCostRep <= 0) )
best Regards,
Chandra
http://chanduas.blogspot.com/
http://groups.msn.com/SQLResource/
---
"Chandra" wrote:
> hi Ivan
>
> This is the equivalent after removing the CASE in Where Clause:
> UPDATE abo_tags
> SET locked = @.PrimaryGroupFilter,
> locking_user = @.user,
> lockingdate = @.sDate
> FROM abo_tags
> INNER JOIN abo ON abo_tags.id_no_abo = abo.id_no
> INNER JOIN products ON abo.id_no_product = products.id_no
> LEFT OUTER JOIN abo_tags_subsidies ON abo_tags.id_no =
> abo_tags_subsidies.id_no_abo_tag
> WHERE
> abo_tags.id_no_invoice_type = 2 and abo_tags.locked in ('0', '',NULL)
> and abo_tags.validity_date >= @.mdatInvoiceFrom
> and abo_tags.validity_date <= @.mdatInvoiceTo
> and abo.id_no_primarygroup in (select primchild from invoicehelp where
> parentkey = @.PrimaryGroupFilter)
> and ((@.mlngProduct > 0 AND abo.id_no_product=@.mlngProduct) OR (@.mlngProduc
t
> <= 0))
> and ((@.mlngSchool > 0 AND abo.id_no_school=@.mlngSchool) OR (@.mlngSchool <=
0
> ))
> and ((@.mlngCostRep > 0 AND abo_tags_subsidies.id_no_costrepresentative =
> @.mlngCostRep) OR (@.mlngCostRep <= 0) )
> I dont thin, there is a problem with the CASE. I believe its because of th
e
> in (select primchild from invoicehelp where
> parentkey = @.PrimaryGroupFilter)
> please let me if this answers your question.
> best Regards,
> Chandra
> http://chanduas.blogspot.com/
> http://groups.msn.com/SQLResource/
> ---
>
> "Ivan Debono" wrote:
>|||Never heard about the Coalesce... need to read more about it.
Is there an alternative for the Subselect (select primchild...)'
Thanks,
Ivan
"Alejandro Mesa" <AlejandroMesa@.discussions.microsoft.com> schrieb im
Newsbeitrag news:7F407540-37EF-4341-946A-78FB74EB0E91@.microsoft.com...
> Ivan,
> Supposing that are int datatype, then try:
> WHERE
> abo_tags.id_no_invoice_type = 2 and abo_tags.locked in ('0', '')
> and abo_tags.validity_date >= @.mdatInvoiceFrom
> and abo_tags.validity_date <= @.mdatInvoiceTo
> and abo.id_no_primarygroup in (
> select primchild
> from invoicehelp
> where
> parentkey = @.PrimaryGroupFilter)
> and abo.id_no_product between coalesce(nullif(@.mlngProduct, 0), 1) and
> coalesce(nullif(@.mlngProduct, 0), 2147483647)
> and abo.id_no_school between coalesce(nullif(@.mlngSchool, 0), 1) and
> coalesce(nullif(@.mlngSchool, 0), 2147483647)
> and abo_tags_subsidies.id_no_costrepresentative between
> coalesce(nullif(@.mlngCostRep, 0), 1) and coalesce(nullif(@.mlngCostRep, 0),
> 2147483647)
> )
> also, take off the null value from the list used with first IN operator.
>
> abo_tags.id_no_invoice_type = 2 and abo_tags.locked in ('0', '')
>
> Dynamic Search Conditions in T-SQL
> http://www.sommarskog.se/dyn-search.html
>
> AMB
> "Ivan Debono" wrote:
>|||I would go thru the DDL and change the blank strings to '0', add a
DEFAULT and a check constraint to prevent this problem in the future.

Monday, March 19, 2012

case

can i use case in an update statement?
UPDATE pn
SET pn.payg_tax = pn.witholdingtax,
pn.witholdingtax = 0
FROM @.PaymentNotification pn
where witholdingtax > 0 and ato_payment_id is null
UPDATE pn
SET pn.witholdingtax = pn.payg_tax,
pn.payg_tax = 0
FROM @.PaymentNotification pn
where witholdingtax > 0 and ato_payment_id is not null
i want to combine teh above 2 statements.You mean like?:
UPDATE
pn
SET
pn.payg_tax=case when ato_payment_id is null then pn.witholdingtax else 0
end,
pn.witholdingtax=case when ato_payment_id is null then 0 else pn.payg_tax
end
FROM
@.PaymentNotification pn
where
witholdingtax>0
"ichor" <ichor@.hotmail.com> wrote in message
news:OwnarL4MGHA.2764@.TK2MSFTNGP10.phx.gbl...
> can i use case in an update statement?
> UPDATE pn
> SET pn.payg_tax = pn.witholdingtax,
> pn.witholdingtax = 0
> FROM @.PaymentNotification pn
> where witholdingtax > 0 and ato_payment_id is null
> UPDATE pn
> SET pn.witholdingtax = pn.payg_tax,
> pn.payg_tax = 0
> FROM @.PaymentNotification pn
> where witholdingtax > 0 and ato_payment_id is not null
> i want to combine teh above 2 statements.
>

Cascading Update And Delete

If we want to maintain the data in relationships.

There are two ways to do it.

1. Auto (Like Cascading Update And Delete)

2. Manually (Like In Stored Procedures)

I read an intresting article

http://imar.spaanjaars.com/QuickDocId.aspx?quickdoc=419

In this article Imar has choosen the second way (Manually).

And when I talk to Imar.

He said, "Cascading deletes would have worked equally well in this situation. However, I personally don't like them too much. I am much rather in control, enabling me to delete what I want and when I want it. I could, for example, keep certain data for "time travelling scenarios" (e.g. the state things were in some time ago) or I might want to keep it for other purposes."

Can any one help me to choose the better one.

Waiting for helpful replies.

Well, I can give you my opinion. I preferer cascading deletes to keep the integrity of my data. If it's something that I want to keep I make a structure for that data. Like a log table or some export function to retrieve the state of something.

To rely on stored procedures to maintain the integrity sounds to error prone for me.

|||

I need more views.

Cascading Triggers

Hi,
I have 3 Tables with After Update Triggers.
They all cascade like City -> Province -> State (as a simplified example)
If I Update a bit (A) in City, a Trigger Sets a bit (B) in Province.
If I Update the bit B in Province, a Trigger Sets a Bit (C) in State.
This works.
However:
If I Set A, a trigger on table City sets B BUT a trigger on table Province
DOESN'T in turn Set C in table State.
So: Individually the Triggers work, but they don't Cascade their action.
Any advise?
TIA,
MichaelHi Michael,
I think I'm having the same problem. I'm hoping to take action via a
trigger on child records when the parent is deleted, but the child table's
trigger doesn't seem to fire. Hopefully someone has a suggestion.
Rgds,
Bill
"Michael Maes" <michael@.merlot.com> wrote in message
news:5BEB7F99-288B-48A8-98DE-F2FBD22AFE75@.microsoft.com...
> Hi,
> I have 3 Tables with After Update Triggers.
> They all cascade like City -> Province -> State (as a simplified example)
> If I Update a bit (A) in City, a Trigger Sets a bit (B) in Province.
> If I Update the bit B in Province, a Trigger Sets a Bit (C) in State.
> This works.
> However:
> If I Set A, a trigger on table City sets B BUT a trigger on table Province
> DOESN'T in turn Set C in table State.
> So: Individually the Triggers work, but they don't Cascade their action.
> Any advise?
> TIA,
>
> Michael
>|||There is a server option "Allow triggers to be fired which fire other
triggers (nested triggers)". Here is the description copied from BO:
1. Expand a server group.
2. Right-click a server, and then click Properties.
3. Click the Server Settings tab.
4. Under Server behavior, select or clear the Allow triggers to be
fired which fire other triggers (nested triggers) check box.
For more information, see Books Online, article "Using Nested Triggers"|||Hi Sergei,
Thanks for your advise!
I just found an article on this:
http://www.sqlservercentral.com/col.../triggers_1.asp
Nested and Recursive Triggers
Nested triggers are triggers that fire due to actions of other triggers.
For instance, I delete a row from TableA. A trigger on TableA fires to
delete rows from TableB. Because I'm deleting rows from TableB, a trigger
fires on TableB to record the deletes. This is an example of a nested
trigger. As we've talked about, SQL Server 7.0 doesn't support cascading
updates and deletes based on foreign key relationships. Therefore, if we
want to relate our data we can't use DRI and must resort to triggers or some
application oversight. Let's say we've got a cascade delete to fire down 3
or 4 tables. Nested triggers are our answer. Our delete on a particular
table fires a trigger which deletes rows for another table, which fires a
trigger, so on and so forth. SQL Server 7 and 2000 support up to 32 levels
of nested triggers.
Now the big question is, does my SQL Server allow nested triggers? That's
an easy question to answer. It's on by default, but in Query Analyzer we ca
n
issue the following command:
EXEC sp_configure 'nested triggers'
If your run_value is set to 0, your server isn't allowing nested triggers.
If it's set to 1, nested triggers may fire. This is a server wide setting.
Now, to change your setting, once again use the sp_configure command:
To turn off nested triggers:
EXEC sp_configure 'nested triggers', 0
RECONFIGURE
To turn on nested triggers:
EXEC sp_configure 'nested triggers', 1
RECONFIGURE
"Sergei Almazov" wrote:

> There is a server option "Allow triggers to be fired which fire other
> triggers (nested triggers)". Here is the description copied from BO:
> 1. Expand a server group.
> 2. Right-click a server, and then click Properties.
> 3. Click the Server Settings tab.
> 4. Under Server behavior, select or clear the Allow triggers to be
> fired which fire other triggers (nested triggers) check box.
> For more information, see Books Online, article "Using Nested Triggers"
>|||I wonder why the defualt setting is off for this. (Protecting us from
potentially faulty programming perhaps?) ;-) Also, seems like it would be
handy to be able to turn it on per table or database, rather than at the
server level.
In my case where I'm just trying to perform some actions first with the
information in detail records that will be deleted, would it be better to
turn off the cascade delete for the related table and handle deleting of the
detail records in the delete trigger of the master table, or is it better to
allow nested triggers?
"Sergei Almazov" <almazik@.ukr.net> wrote in message
news:1127473954.892200.319820@.g43g2000cwa.googlegroups.com...
> There is a server option "Allow triggers to be fired which fire other
> triggers (nested triggers)". Here is the description copied from BO:
> 1. Expand a server group.
> 2. Right-click a server, and then click Properties.
> 3. Click the Server Settings tab.
> 4. Under Server behavior, select or clear the Allow triggers to be
> fired which fire other triggers (nested triggers) check box.
> For more information, see Books Online, article "Using Nested Triggers"
>|||I wonder why the defualt setting is off for this. (Protecting us from
potentially faulty programming perhaps?) ;-) Also, seems like it would be
handy to be able to turn it on per table or database, rather than at the
server level.
In my case where I'm just trying to perform some actions first with the
information in detail records that will be deleted, would it be better to
turn off the cascade delete for the related table and handle deleting of the
detail records in the delete trigger of the master table, or is it better to
allow nested triggers?
"Sergei Almazov" <almazik@.ukr.net> wrote in message
news:1127473954.892200.319820@.g43g2000cwa.googlegroups.com...
> There is a server option "Allow triggers to be fired which fire other
> triggers (nested triggers)". Here is the description copied from BO:
> 1. Expand a server group.
> 2. Right-click a server, and then click Properties.
> 3. Click the Server Settings tab.
> 4. Under Server behavior, select or clear the Allow triggers to be
> fired which fire other triggers (nested triggers) check box.
> For more information, see Books Online, article "Using Nested Triggers"
>|||Hi Bill,
What scares me is that someone or something else can disable your nested
triggers because it's DataServer-Wide :-(((
"Bill Hicks" wrote:

> I wonder why the defualt setting is off for this. (Protecting us from
> potentially faulty programming perhaps?) ;-) Also, seems like it would be
> handy to be able to turn it on per table or database, rather than at the
> server level.
> In my case where I'm just trying to perform some actions first with the
> information in detail records that will be deleted, would it be better to
> turn off the cascade delete for the related table and handle deleting of t
he
> detail records in the delete trigger of the master table, or is it better
to
> allow nested triggers?
> "Sergei Almazov" <almazik@.ukr.net> wrote in message
> news:1127473954.892200.319820@.g43g2000cwa.googlegroups.com...
>
>

Cascading Parameters problem

Are there any way to update parameter values first after a several Cascading Parameters (text fileds) is set?

Ex:
First I would like to fill the parameter fields (text fields):
From Date - To Date,
From Customer - To Customer

then the process begins to filter the rest of the fields values.

ChristoferYou could put the fields that you want filtered by the Date and Customer into a subreport then filter the subreport by the value in the Date and Customer fields.

Thursday, March 8, 2012

Cascade updates

I ran a bulk update on a SQL database for a range between dateswhere there
were trigger and possibly foreign keys. the parent updated fine but it
changed multiple child records although they were not relatedHi
Can you show us DDL + sample data + your query?
"Dangerfield" <Dangerfield@.discussions.microsoft.com> wrote in message
news:2E57BC94-A3B0-46CA-9349-C2DEB7C79F46@.microsoft.com...
> I ran a bulk update on a SQL database for a range between dateswhere there
> were trigger and possibly foreign keys. the parent updated fine but it
> changed multiple child records although they were not related

Cascade Update and Delete Related Fields..

I am building tables using the database diagram with enterprise manager. One of the options available is to "Cascade Update and Delete Related Fields". I think this means that if I change a PK Identifier in a table all related FK's will be updated to the new value and if I delete the PK all related FK records will be deleted. Is this correct? Is this a good idea to do something like this?

I have always handled what needs to be changed using SP's following business rules. A friend has been preaching the use of the "Cascade Update and Delete Related Fields" functionality provided with the database.

Please let me know what you think.

ThanksAs you already mention, I think this is a matter of opinion. The advantage for cascading is that you don't have to do any checking and programming to avoid data inconstency. Disadvantage is that you don't have any control about the updates/deletes of the related records. For the manual programming through sp's it's offcourse the other way around.
In other words: you have to see in every situation what's the best solution.

cascade update / foreign key

Hi!
For the sake of simplicity, I have three tables, Employee, Department and
Work

Employee >-- Department
\ /
\ /
^ ^
Work

The Work table have two columns, empno and depno and consists that the
employee has worked on another department.

Here is my scripts:
create table employee (empno int not null primary key, depno int not null)
create table department (depno int not null primary key)
create table work (empno int not null, depno int not null)

alter table employee add constraint fk_employee_department foreign key
(depno)
references department (depno)
on update cascade

alter table work add constraint fk_work_employee foreign key (empno)
references employee (empno)
on update cascade

alter table work add constraint fk_work_department foreign key (depno)
references department (depno)
on update cascade

My problem is the last command. SQL Server responds:
Server: Msg 1785, Level 16, State 1, Line 1
Introducing FOREIGN KEY constraint 'fk_work_department' on table 'work' may
cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON
UPDATE NO ACTION, or modify other FOREIGN KEY constraints.

But I want the depno in the work table to be updated when a department.depno
changes a value.

Does anyone have a suggestion on how to overcome this problem?

Thanks in advance

Best regards,
Gunnar Vyenli
EDB-konsulent as
NORWAYHi,

SQL statement that you had provided is generating circular refrence in
updates
Workaround is to use triger instead of foreign key integrity.

Comment the one of foriegn key sql and use triger.

Note this trigger are not tested. but is only for your reference and
other work around for problem.

/*alter table work add constraint fk_work_employee foreign key (empno)
references employee (empno)
on update cascade
go
*/

create trigger trgUpdateEmpNoInDept
on employee
for update
as
set nocount on

declare @.NewEmpno int , @.OldEmpno int

select @.NewEmpno = inserted.empno from inserted
select @.OldEmpno = deleted.empno from deleted

update work set work.empno = @.NewEmpno
where work.empno = @.OldEmpno
if @.@.rowcount=0 or @.@.error<>0
begin
Rollback tran
end

set nocount off
go

create trigger trgCheckEmpExists
on Work
For Update
as

set nocount on

declare @.NewEmpno int
select @.NewEmpno = inserted.empno from inserted

If Not Exists (Select * from employee where empno = @.NewEmpno )
Begin
RAISERROR ('Empno do not exists', 16, 1)
Rollback Tran
End
set nocount off

go

Thanks & Regards, Amit

"Gunnar Vyenli" <gv@.edbkonsulent.no> wrote in message news:<3f6a24cb$1@.news.broadpark.no>...
> Hi!
> For the sake of simplicity, I have three tables, Employee, Department and
> Work
> Employee >-- Department
> \ /
> \ /
> ^ ^
> Work
> The Work table have two columns, empno and depno and consists that the
> employee has worked on another department.
> Here is my scripts:
> create table employee (empno int not null primary key, depno int not null)
> create table department (depno int not null primary key)
> create table work (empno int not null, depno int not null)
> alter table employee add constraint fk_employee_department foreign key
> (depno)
> references department (depno)
> on update cascade
> alter table work add constraint fk_work_employee foreign key (empno)
> references employee (empno)
> on update cascade
> alter table work add constraint fk_work_department foreign key (depno)
> references department (depno)
> on update cascade
> My problem is the last command. SQL Server responds:
> Server: Msg 1785, Level 16, State 1, Line 1
> Introducing FOREIGN KEY constraint 'fk_work_department' on table 'work' may
> cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON
> UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
> But I want the depno in the work table to be updated when a department.depno
> changes a value.
> Does anyone have a suggestion on how to overcome this problem?
> Thanks in advance
> Best regards,
> Gunnar Vyenli
> EDB-konsulent as
> NORWAY|||Thank you very much!
-Gunnar

"AMIT" <amitb@.zenithinfotech.com> wrote in message
news:f3093a66.0309182236.2313bc10@.posting.google.c om...
> Hi,
>
> SQL statement that you had provided is generating circular refrence in
> updates
> Workaround is to use triger instead of foreign key integrity.
> Comment the one of foriegn key sql and use triger.
> Note this trigger are not tested. but is only for your reference and
> other work around for problem.
> /*alter table work add constraint fk_work_employee foreign key (empno)
> references employee (empno)
> on update cascade
> go
> */
>
> create trigger trgUpdateEmpNoInDept
> on employee
> for update
> as
> set nocount on
> declare @.NewEmpno int , @.OldEmpno int
> select @.NewEmpno = inserted.empno from inserted
> select @.OldEmpno = deleted.empno from deleted
> update work set work.empno = @.NewEmpno
> where work.empno = @.OldEmpno
> if @.@.rowcount=0 or @.@.error<>0
> begin
> Rollback tran
> end
> set nocount off
> go
> create trigger trgCheckEmpExists
> on Work
> For Update
> as
> set nocount on
> declare @.NewEmpno int
> select @.NewEmpno = inserted.empno from inserted
> If Not Exists (Select * from employee where empno = @.NewEmpno )
> Begin
> RAISERROR ('Empno do not exists', 16, 1)
> Rollback Tran
> End
> set nocount off
> go
>
> Thanks & Regards, Amit
> "Gunnar Vyenli" <gv@.edbkonsulent.no> wrote in message
news:<3f6a24cb$1@.news.broadpark.no>...
> > Hi!
> > For the sake of simplicity, I have three tables, Employee, Department
and
> > Work
> > Employee >-- Department
> > \ /
> > \ /
> > ^ ^
> > Work
> > The Work table have two columns, empno and depno and consists that the
> > employee has worked on another department.
> > Here is my scripts:
> > create table employee (empno int not null primary key, depno int not
null)
> > create table department (depno int not null primary key)
> > create table work (empno int not null, depno int not null)
> > alter table employee add constraint fk_employee_department foreign key
> > (depno)
> > references department (depno)
> > on update cascade
> > alter table work add constraint fk_work_employee foreign key (empno)
> > references employee (empno)
> > on update cascade
> > alter table work add constraint fk_work_department foreign key (depno)
> > references department (depno)
> > on update cascade
> > My problem is the last command. SQL Server responds:
> > Server: Msg 1785, Level 16, State 1, Line 1
> > Introducing FOREIGN KEY constraint 'fk_work_department' on table 'work'
may
> > cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or
ON
> > UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
> > But I want the depno in the work table to be updated when a
department.depno
> > changes a value.
> > Does anyone have a suggestion on how to overcome this problem?
> > Thanks in advance
> > Best regards,
> > Gunnar Vyenli
> > EDB-konsulent as
> > NORWAY

Cascade Update

Does anyone know how to do a cascade update in SQL 2005 using the studio manager?

Basically, I have a project table with a status column. If the status is set to 2, then I need to update another table that references the project id.

You can create a foreign key with cascading. For example you have 2 tables: the referenced table tbl1 with projectid as primary key, and the referencing table tbl2 with projectid column:

Alter Table tbl2 Add
Constraint fk_tbl2_projectid
Foreign Key (projectid)
References tbl1(projectid)
On Update Cascade

You can get more information from these links:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_aa-az_3ied.asp

And

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/createdb/cm_8_des_04_92ib.asp

Wednesday, March 7, 2012

carriage return inside a field of text data type?

how can i insert a carriage return when i update the field?

say i want to put the following inside a field:
firstline
secondline

how can i update/insert a column to have a return carriage inside it?
UPDATE table SET column = 'firstline secondline'

the reason i want this is because when using a program (Solomon, by microsoft, purchasing software) to grab a field out of the database and when it displays that field in the programs textbox, i want it to be displayed on two separate lines

i tried doing
UPDATE table SET column = 'firstline' + char(13) 'secondline'

but when in the solomon program, it displays an ascii character between firstline and secondline like: firstline||secondline

thankstry char(10) instead
or the combination of the two characters|||ive actually tried them both :(

edit: just tried using char(13) + char(10) and it works! thanks!|||you welcome ;)

carriage return in a text field

We are in the process of updating a Text column.
How can we update the row and column and add a carriage return to the
existing text?A carriage return character is an ASCII 13 character. So if you wanted
foo
bar
then you would say
select 'foo' + char(13) + 'bar'
However, in the Windows world, carriage returns are normally paired with
line feed characters (Unix apps typically just have the CR with no LF).
A line feed character is ASCII 10. So a CR/LF pair would be
select 'foo' + char(13) + char(10) + 'bar'
Hope this helps.
*mike hodgson*
http://sqlnerd.blogspot.com
wnfisba wrote:

>We are in the process of updating a Text column.
>How can we update the row and column and add a carriage return to the
>existing text?
>

Friday, February 24, 2012

Capture the ID of the last record entered and use in an Update

I'm entering a Selection record for a partiuclar lotID,

Once entered, I need to obtain its SelectionID then use it to update a another field within that record.

Here's what I've been doing...

--insert values into a testchangeorders table

INSERT

INTO testchangeordersVALUES(2,3,3,3,1,'red',0,5)

--Find the SelectionsID of the last record created for that partiuclar LotID

SELECT

MAX(SelectionsID)

FROM

testchangeorders

WHERE

LotID= 2

--Once located, I was trying to update a field called uniqueID with a contantination of '3-' & the record's SelectionsID

UPDATE

testchangeorders

SET

UniqueID=('3-'& SelectionID

WHERE

SelectionsID=SELECTMAX(SelectionsID)AND LotID= 2)

If your SelectionsID is a identity field Use

select@.@.identity

after your insert statement.It returns the last identity value created in the cureent scope.

Have this code in a stored procedure along with the insert statement

Hope this will help you. Let me Know if you need any further help

|||Actually, you'll want to use SELECT SCOPE_IDENTITY() if you want it limited to the current scope. @.@.IDENTITY is only limited to the current session, not the current scope.|||

SCOPE_IDENTITY and @.@.IDENTITY will return last identity values generated in any table in the current session. However, SCOPE_IDENTITY returns values inserted only within the current scope; @.@.IDENTITY is not limited to a specific scope.

For example, you have two tables, T1 and T2, and an INSERT trigger defined on T1. When a row is inserted to T1, the trigger fires and inserts a row in T2. This scenario illustrates two scopes: the insert on T1, and the insert on T2 as a result of the trigger.

Assuming that both T1 and T2 have IDENTITY columns, @.@.IDENTITY and SCOPE_IDENTITY will return different values at the end of an INSERT statement on T1.

@.@.IDENTITY will return the last IDENTITY column value inserted across any scope in the current session, which is the value inserted in T2.

SCOPE_IDENTITY() will return the IDENTITY value inserted in T1, which was the last INSERT that occurred in the same scope. The SCOPE_IDENTITY() function will return the NULL value if the function is invoked before any insert statements into an identity column occur in the scope.

See Examples for an illustration.

Examples

This example creates two tables,TZ andTY, and an INSERT trigger onTZ. When a row is inserted to tableTZ, the trigger (Ztrig) fires and inserts a row inTY.

USE tempdb
GO
CREATE TABLE TZ (
Z_id int IDENTITY(1,1)PRIMARY KEY,
Z_name varchar(20) NOT NULL)

INSERT TZ
VALUES ('Lisa')
INSERT TZ
VALUES ('Mike')
INSERT TZ
VALUES ('Carla')

SELECT * FROM TZ

--Result set: This is how table TZ looks
Z_id Z_name
----
1 Lisa
2 Mike
3 Carla

CREATE TABLE TY (
Y_id int IDENTITY(100,5)PRIMARY KEY,
Y_name varchar(20) NULL)

INSERT TY (Y_name)
VALUES ('boathouse')
INSERT TY (Y_name)
VALUES ('rocks')
INSERT TY (Y_name)
VALUES ('elevator')

SELECT * FROM TY
--Result set: This is how TY looks:
Y_id Y_name
-----
100 boathouse
105 rocks
110 elevator

/*Create the trigger that inserts a row in table TY
when a row is inserted in table TZ*/
CREATE TRIGGER Ztrig
ON TZ
FOR INSERT AS
BEGIN
INSERT TY VALUES ('')
END

/*FIRE the trigger and find out what identity values you get
with the @.@.IDENTITY and SCOPE_IDENTITY functions*/
INSERT TZ VALUES ('Rosalie')

SELECT SCOPE_IDENTITY() AS [SCOPE_IDENTITY]
GO
SELECT @.@.IDENTITY AS [@.@.IDENTITY]
GO

--Here is the result set.
SCOPE_IDENTITY
4
/*SCOPE_IDENTITY returned the last identity value in the same scope, which was the insert on table TZ*/

@.@.IDENTITY
115
/*@.@.IDENTITY returned the last identity value inserted to TY by the trigger, which fired due to an earlier insert on TZ*/

 
 
SQL Server Books Online
 
HTH 
|||

Thanks-each of you who responded.

I read and reread the last post explaining @.@.IDENTITY and SELECT SCOPE_IDENTITY(). I'm a little fuzzy as to why one would even use @.@.IDENTITY, unless in my case it doesn't matter.

I'm using the following code and if I use @.@.IDENTITY is seems to work just as well what I have below

INSERT

INTO testchangeordersVALUES(2,3,3,3,1,'red',0,5)

UPDATE

testchangeordersSET UniqueID='3-'+CONVERT(varchar,SCOPE_IDENTITY())

WHERE

SelectionsID=SCOPE_IDENTITY()

It updates the UniqueID with a "3-#" (PK) just as I want it to ie., 3-71

I guess my question is, in my case many users will be hitting this at the same time:

If user A fires it and creates ID# 22, the UniqueID should be 3-22

If user B fires it and creates ID#23, the UniqueID should be 3-23

By going with Scope_Identity() does that guarantee that records are being updated correctly? I understand why to use scope if you are updating two tables but don't know if it matters if you are working in the same table (which may be why I was advised to use @.@.IDENTITY in the first place).

I think I'm ok because the condition is WHERE SelectionsID = SCOPE_IDENTITY and that should make sure the correct one is updated.

|||

I'd say 99.9% of the time when someone wants to get the last identity created, they want to be using SCOPE_IDENTITY(). You don't need to worry about either of them getting confused by concurrent users, though, since they are both per-session. The difference generally comes into play when you have triggers on tables that will automatically create records in other tables after an action in your sproc. In that case @.@.IDENTITY will get the last identity created by the session *in any table*.

|||

Have a look into this.

http://dlanouette.blogspot.com/2005/05/sql-identity-vs-scopeidentity.html

http://www.sql-server-performance.com/forum/topic.asp?TOPIC_ID=10434

Hope this may help you

|||

I'm clear now thanks.

AshokRaja - thanks too. That first link in particular was good.

Capture Result of Update?

I have an Update statement in a stored procedure, and I want to capture
the number of rows affected for returning to the caller. If this was a
simple Insert, I'd use Scope_Identity() to get the Identity. But in
this case I want the count of all updated rows.
Thanks.
You want to use either @.@.RowCount (or RowCount_Big() if there is any
possibility that more than 2 billion rows may be affected by the Update
statement.
Something like:
Declare @.UpdateCount int
Update Mytable Set ... Where ...
Select @.UpdateCount = @.@.RowCount
Tom
Then @.UpdateCount will contain the number of rows which matched the Where
clause in your Update statement.
<bradwiseathome@.hotmail.com> wrote in message
news:1143750464.490863.149600@.v46g2000cwv.googlegr oups.com...
>I have an Update statement in a stored procedure, and I want to capture
> the number of rows affected for returning to the caller. If this was a
> simple Insert, I'd use Scope_Identity() to get the Identity. But in
> this case I want the count of all updated rows.
> Thanks.
>

Sunday, February 19, 2012

Capture Error In DTS Package

I have a SQL Server Package that is dumping a text file into an Access
Database. However, due to update timing every now and then it errors
out due to a primary key violation. How do I capture that error
number in my next Active Script Task and determine whether or not I
want to continue (since if it's a duplicate I just want to skip it and
finish the DTS package). If it's a different error I want to log
it.
Thanks!Hi
If these are identity values you may want to check out
http://www.sqldts.com/293.aspx
if not try
http://www.sqldts.com/282.aspx
John
"Creative" wrote:

> I have a SQL Server Package that is dumping a text file into an Access
> Database. However, due to update timing every now and then it errors
> out due to a primary key violation. How do I capture that error
> number in my next Active Script Task and determine whether or not I
> want to continue (since if it's a duplicate I just want to skip it and
> finish the DTS package). If it's a different error I want to log
> it.
> Thanks!
>|||On Nov 27, 3:00 am, John Bell <jbellnewspo...@.hotmail.com> wrote:
> Hi
> If these are identity values you may want to check outhttp://www.sqldts.co
m/293.aspx
> if not tryhttp://www.sqldts.com/282.aspx
> John
>
> "Creative" wrote:
>
> - Show quoted text -
Thanks for the reply but it doesn't look like that answers my
question. I'm actually using a File Transformation from a text file
to an access database. I have a connection to the text file and a
connection to an access database with a transformation connecting the
two.|||Hi
There was no mention of the destination database being an access database,
in your original post. I suggest that you therefore load into a staging tabl
e
and either do an update if the PK exists or an insert if it doesn't.
John
"Creative" wrote:

> On Nov 27, 3:00 am, John Bell <jbellnewspo...@.hotmail.com> wrote:
> Thanks for the reply but it doesn't look like that answers my
> question. I'm actually using a File Transformation from a text file
> to an access database. I have a connection to the text file and a
> connection to an access database with a transformation connecting the
> two.
>|||I don't know the answer, but it's a good question, and I'm in a
similar situation in SSIS - except I want to test for a warning code!
Googling found this crufty answer:
http://www.quest-pipelines.com/newsletter-v4/0603_E.htm
There may be a better answer if you open up the multiphase data pump
business, but I have small experience with that.
Note there is also a DTS group, I'll copy this to.
Josh
On Mon, 26 Nov 2007 13:54:33 -0800 (PST), Creative <GraberJ@.gmail.com>
wrote:

>I have a SQL Server Package that is dumping a text file into an Access
>Database. However, due to update timing every now and then it errors
>out due to a primary key violation. How do I capture that error
>number in my next Active Script Task and determine whether or not I
>want to continue (since if it's a duplicate I just want to skip it and
>finish the DTS package). If it's a different error I want to log
>it.
>Thanks!|||Hi Josh
I pointed the OP to the tutorial on Multiphase datapump on SQL DTS. In SSIS
you have a standarderrorvariable which may be of some use to you, and there
is the configure error output dialog. you may want to check out Professional
SQL Server 2005 Integration Services by Brian Knight et al ISBN 0764584359 o
r
the short videos on http://www.jumpstarttv.com such as
http://www.jumpstarttv.com/Media.aspx?vid=34 where Brian shows how an
application similar to the examples in the book work.
John
"JXStern" wrote:

> I don't know the answer, but it's a good question, and I'm in a
> similar situation in SSIS - except I want to test for a warning code!
> Googling found this crufty answer:
> http://www.quest-pipelines.com/newsletter-v4/0603_E.htm
> There may be a better answer if you open up the multiphase data pump
> business, but I have small experience with that.
> Note there is also a DTS group, I'll copy this to.
> Josh
>
> On Mon, 26 Nov 2007 13:54:33 -0800 (PST), Creative <GraberJ@.gmail.com>
> wrote:
>
>|||John,
Thanks for several good hints, I'll be following them all. Configure error
output dialog?!?! Oh, in a data flow. Righto.
I keep waiting for some other, newer SSIS books to come out.
I've got the basics grinding along now, anyway.
Thanks again.
Josh
"John Bell" wrote:
[vbcol=seagreen]
> Hi Josh
> I pointed the OP to the tutorial on Multiphase datapump on SQL DTS. In SSI
S
> you have a standarderrorvariable which may be of some use to you, and ther
e
> is the configure error output dialog. you may want to check out Profession
al
> SQL Server 2005 Integration Services by Brian Knight et al ISBN 0764584359
or
> the short videos on http://www.jumpstarttv.com such as
> http://www.jumpstarttv.com/Media.aspx?vid=34 where Brian shows how an
> application similar to the examples in the book work.
> John
> "JXStern" wrote:
>

Capture Error In DTS Package

I have a SQL Server Package that is dumping a text file into an Access
Database. However, due to update timing every now and then it errors
out due to a primary key violation. How do I capture that error
number in my next Active Script Task and determine whether or not I
want to continue (since if it's a duplicate I just want to skip it and
finish the DTS package). If it's a different error I want to log
it.
Thanks!Hi
If these are identity values you may want to check out
http://www.sqldts.com/293.aspx
if not try
http://www.sqldts.com/282.aspx
John
"Creative" wrote:
> I have a SQL Server Package that is dumping a text file into an Access
> Database. However, due to update timing every now and then it errors
> out due to a primary key violation. How do I capture that error
> number in my next Active Script Task and determine whether or not I
> want to continue (since if it's a duplicate I just want to skip it and
> finish the DTS package). If it's a different error I want to log
> it.
> Thanks!
>|||On Nov 27, 3:00 am, John Bell <jbellnewspo...@.hotmail.com> wrote:
> Hi
> If these are identity values you may want to check outhttp://www.sqldts.com/293.aspx
> if not tryhttp://www.sqldts.com/282.aspx
> John
>
> "Creative" wrote:
> > I have a SQL Server Package that is dumping a text file into an Access
> > Database. However, due to update timing every now and then it errors
> > out due to a primary key violation. How do I capture that error
> > number in my next Active Script Task and determine whether or not I
> > want to continue (since if it's a duplicate I just want to skip it and
> > finish the DTS package). If it's a different error I want to log
> > it.
> > Thanks!- Hide quoted text -
> - Show quoted text -
Thanks for the reply but it doesn't look like that answers my
question. I'm actually using a File Transformation from a text file
to an access database. I have a connection to the text file and a
connection to an access database with a transformation connecting the
two.|||Hi
There was no mention of the destination database being an access database,
in your original post. I suggest that you therefore load into a staging table
and either do an update if the PK exists or an insert if it doesn't.
John
"Creative" wrote:
> On Nov 27, 3:00 am, John Bell <jbellnewspo...@.hotmail.com> wrote:
> > Hi
> >
> > If these are identity values you may want to check outhttp://www.sqldts.com/293.aspx
> > if not tryhttp://www.sqldts.com/282.aspx
> >
> > John
> >
> >
> >
> > "Creative" wrote:
> > > I have a SQL Server Package that is dumping a text file into an Access
> > > Database. However, due to update timing every now and then it errors
> > > out due to a primary key violation. How do I capture that error
> > > number in my next Active Script Task and determine whether or not I
> > > want to continue (since if it's a duplicate I just want to skip it and
> > > finish the DTS package). If it's a different error I want to log
> > > it.
> >
> > > Thanks!- Hide quoted text -
> >
> > - Show quoted text -
> Thanks for the reply but it doesn't look like that answers my
> question. I'm actually using a File Transformation from a text file
> to an access database. I have a connection to the text file and a
> connection to an access database with a transformation connecting the
> two.
>|||I don't know the answer, but it's a good question, and I'm in a
similar situation in SSIS - except I want to test for a warning code!
Googling found this crufty answer:
http://www.quest-pipelines.com/newsletter-v4/0603_E.htm
There may be a better answer if you open up the multiphase data pump
business, but I have small experience with that.
Note there is also a DTS group, I'll copy this to.
Josh
On Mon, 26 Nov 2007 13:54:33 -0800 (PST), Creative <GraberJ@.gmail.com>
wrote:
>I have a SQL Server Package that is dumping a text file into an Access
>Database. However, due to update timing every now and then it errors
>out due to a primary key violation. How do I capture that error
>number in my next Active Script Task and determine whether or not I
>want to continue (since if it's a duplicate I just want to skip it and
>finish the DTS package). If it's a different error I want to log
>it.
>Thanks!|||Hi Josh
I pointed the OP to the tutorial on Multiphase datapump on SQL DTS. In SSIS
you have a standarderrorvariable which may be of some use to you, and there
is the configure error output dialog. you may want to check out Professional
SQL Server 2005 Integration Services by Brian Knight et al ISBN 0764584359 or
the short videos on http://www.jumpstarttv.com such as
http://www.jumpstarttv.com/Media.aspx?vid=34 where Brian shows how an
application similar to the examples in the book work.
John
"JXStern" wrote:
> I don't know the answer, but it's a good question, and I'm in a
> similar situation in SSIS - except I want to test for a warning code!
> Googling found this crufty answer:
> http://www.quest-pipelines.com/newsletter-v4/0603_E.htm
> There may be a better answer if you open up the multiphase data pump
> business, but I have small experience with that.
> Note there is also a DTS group, I'll copy this to.
> Josh
>
> On Mon, 26 Nov 2007 13:54:33 -0800 (PST), Creative <GraberJ@.gmail.com>
> wrote:
> >I have a SQL Server Package that is dumping a text file into an Access
> >Database. However, due to update timing every now and then it errors
> >out due to a primary key violation. How do I capture that error
> >number in my next Active Script Task and determine whether or not I
> >want to continue (since if it's a duplicate I just want to skip it and
> >finish the DTS package). If it's a different error I want to log
> >it.
> >
> >Thanks!
>|||John,
Thanks for several good hints, I'll be following them all. Configure error
output dialog?!?! Oh, in a data flow. Righto.
I keep waiting for some other, newer SSIS books to come out.
I've got the basics grinding along now, anyway.
Thanks again.
Josh
"John Bell" wrote:
> Hi Josh
> I pointed the OP to the tutorial on Multiphase datapump on SQL DTS. In SSIS
> you have a standarderrorvariable which may be of some use to you, and there
> is the configure error output dialog. you may want to check out Professional
> SQL Server 2005 Integration Services by Brian Knight et al ISBN 0764584359 or
> the short videos on http://www.jumpstarttv.com such as
> http://www.jumpstarttv.com/Media.aspx?vid=34 where Brian shows how an
> application similar to the examples in the book work.
> John
> "JXStern" wrote:
> > I don't know the answer, but it's a good question, and I'm in a
> > similar situation in SSIS - except I want to test for a warning code!
> >
> > Googling found this crufty answer:
> > http://www.quest-pipelines.com/newsletter-v4/0603_E.htm
> >
> > There may be a better answer if you open up the multiphase data pump
> > business, but I have small experience with that.
> >
> > Note there is also a DTS group, I'll copy this to.
> >
> > Josh
> >
> >
> > On Mon, 26 Nov 2007 13:54:33 -0800 (PST), Creative <GraberJ@.gmail.com>
> > wrote:
> >
> > >I have a SQL Server Package that is dumping a text file into an Access
> > >Database. However, due to update timing every now and then it errors
> > >out due to a primary key violation. How do I capture that error
> > >number in my next Active Script Task and determine whether or not I
> > >want to continue (since if it's a duplicate I just want to skip it and
> > >finish the DTS package). If it's a different error I want to log
> > >it.
> > >
> > >Thanks!
> >
> >

Capture Error In DTS Package

I have a SQL Server Package that is dumping a text file into an Access
Database. However, due to update timing every now and then it errors
out due to a primary key violation. How do I capture that error
number in my next Active Script Task and determine whether or not I
want to continue (since if it's a duplicate I just want to skip it and
finish the DTS package). If it's a different error I want to log
it.
Thanks!
Hi
If these are identity values you may want to check out
http://www.sqldts.com/293.aspx
if not try
http://www.sqldts.com/282.aspx
John
"Creative" wrote:

> I have a SQL Server Package that is dumping a text file into an Access
> Database. However, due to update timing every now and then it errors
> out due to a primary key violation. How do I capture that error
> number in my next Active Script Task and determine whether or not I
> want to continue (since if it's a duplicate I just want to skip it and
> finish the DTS package). If it's a different error I want to log
> it.
> Thanks!
>
|||On Nov 27, 3:00 am, John Bell <jbellnewspo...@.hotmail.com> wrote:
> Hi
> If these are identity values you may want to check outhttp://www.sqldts.com/293.aspx
> if not tryhttp://www.sqldts.com/282.aspx
> John
>
> "Creative" wrote:
>
> - Show quoted text -
Thanks for the reply but it doesn't look like that answers my
question. I'm actually using a File Transformation from a text file
to an access database. I have a connection to the text file and a
connection to an access database with a transformation connecting the
two.
|||Hi
There was no mention of the destination database being an access database,
in your original post. I suggest that you therefore load into a staging table
and either do an update if the PK exists or an insert if it doesn't.
John
"Creative" wrote:

> On Nov 27, 3:00 am, John Bell <jbellnewspo...@.hotmail.com> wrote:
> Thanks for the reply but it doesn't look like that answers my
> question. I'm actually using a File Transformation from a text file
> to an access database. I have a connection to the text file and a
> connection to an access database with a transformation connecting the
> two.
>
|||I don't know the answer, but it's a good question, and I'm in a
similar situation in SSIS - except I want to test for a warning code!
Googling found this crufty answer:
http://www.quest-pipelines.com/newsletter-v4/0603_E.htm
There may be a better answer if you open up the multiphase data pump
business, but I have small experience with that.
Note there is also a DTS group, I'll copy this to.
Josh
On Mon, 26 Nov 2007 13:54:33 -0800 (PST), Creative <GraberJ@.gmail.com>
wrote:

>I have a SQL Server Package that is dumping a text file into an Access
>Database. However, due to update timing every now and then it errors
>out due to a primary key violation. How do I capture that error
>number in my next Active Script Task and determine whether or not I
>want to continue (since if it's a duplicate I just want to skip it and
>finish the DTS package). If it's a different error I want to log
>it.
>Thanks!
|||Hi Josh
I pointed the OP to the tutorial on Multiphase datapump on SQL DTS. In SSIS
you have a standarderrorvariable which may be of some use to you, and there
is the configure error output dialog. you may want to check out Professional
SQL Server 2005 Integration Services by Brian Knight et al ISBN 0764584359 or
the short videos on http://www.jumpstarttv.com such as
http://www.jumpstarttv.com/Media.aspx?vid=34 where Brian shows how an
application similar to the examples in the book work.
John
"JXStern" wrote:

> I don't know the answer, but it's a good question, and I'm in a
> similar situation in SSIS - except I want to test for a warning code!
> Googling found this crufty answer:
> http://www.quest-pipelines.com/newsletter-v4/0603_E.htm
> There may be a better answer if you open up the multiphase data pump
> business, but I have small experience with that.
> Note there is also a DTS group, I'll copy this to.
> Josh
>
> On Mon, 26 Nov 2007 13:54:33 -0800 (PST), Creative <GraberJ@.gmail.com>
> wrote:
>
>
|||John,
Thanks for several good hints, I'll be following them all. Configure error
output dialog?!?! Oh, in a data flow. Righto.
I keep waiting for some other, newer SSIS books to come out.
I've got the basics grinding along now, anyway.
Thanks again.
Josh
"John Bell" wrote:
[vbcol=seagreen]
> Hi Josh
> I pointed the OP to the tutorial on Multiphase datapump on SQL DTS. In SSIS
> you have a standarderrorvariable which may be of some use to you, and there
> is the configure error output dialog. you may want to check out Professional
> SQL Server 2005 Integration Services by Brian Knight et al ISBN 0764584359 or
> the short videos on http://www.jumpstarttv.com such as
> http://www.jumpstarttv.com/Media.aspx?vid=34 where Brian shows how an
> application similar to the examples in the book work.
> John
> "JXStern" wrote:

Capture Before/After data on Multirow Updates

Problem: I only get one record of before and after data when performing
multirow updates from a single update statement. I want to get before and
after data for ALL updated records from the update statement. How can I do
this? I am using sp_trace_generateevent to capture before and after data in
a trace when performing updates using the following code:
CREATE TRIGGER [AUDITED] ON [dbo].[authors] FOR UPDATE NOT FOR REPLICATION AS
BEGIN
PRINT 'HERE'
Declare @.mval nvarchar(256)
Declare @.mval2 nvarchar(256)
Declare @.mvalall nvarchar(512)
SELECT
@.mval = ' UPDATE: Before First Name: ' + au_fname + ' -
' + ' Last Name: ' + au_lname + ' | '
FROM DELETED
SELECT
@.mval2 = ' After First Name: ' + au_fname + ' - ' + '
Last Name: ' + au_lname + ' | '
FROM INSERTED
Set @.mvalall=@.mval + @.mval2
EXEC sp_trace_generateevent
@.event_class = 82, @.userinfo=@.mvalall
END
You can't assign multiple row values to a single variable. SQL just returns
the first row values -as you noticed.
For your test, change the code to
SELECT * FROM inserted
SELECT * FROM deleted
to see what is in the tables.
Provide more detail about what you are hoping to accomplish and we can help
you better.
Arnie Rowland, Ph.D.
Westwood Consulting, Inc
Most good judgment comes from experience.
Most experience comes from bad judgment.
- Anonymous
You can't help someone get up a hill without getting a little closer to the
top yourself.
- H. Norman Schwarzkopf
"Ymerejtrebor" <Ymerejtrebor@.discussions.microsoft.com> wrote in message
news:CD971923-195E-464C-A51B-E447526EF7ED@.microsoft.com...
> Problem: I only get one record of before and after data when performing
> multirow updates from a single update statement. I want to get before and
> after data for ALL updated records from the update statement. How can I
> do
> this? I am using sp_trace_generateevent to capture before and after data
> in
> a trace when performing updates using the following code:
> CREATE TRIGGER [AUDITED] ON [dbo].[authors] FOR UPDATE NOT FOR REPLICATION
> AS
> BEGIN
> PRINT 'HERE'
> Declare @.mval nvarchar(256)
> Declare @.mval2 nvarchar(256)
> Declare @.mvalall nvarchar(512)
> SELECT
> @.mval = ' UPDATE: Before First Name: ' + au_fname + ' -
> ' + ' Last Name: ' + au_lname + ' | '
> FROM DELETED
> SELECT
> @.mval2 = ' After First Name: ' + au_fname + ' - ' + '
> Last Name: ' + au_lname + ' | '
> FROM INSERTED
> Set @.mvalall=@.mval + @.mval2
> EXEC sp_trace_generateevent
> @.event_class = 82, @.userinfo=@.mvalall
> END
>

Capture Before/After Data from Multirow Update

Problem: I only get one record of before and after data when performing
multirow updates from a single update statement. I want to get before and
after data for ALL updated records from the update statement. How can I do
this? I am using sp_trace_generateevent to capture before and after data i
n
a trace when performing updates using the following code:
CREATE TRIGGER [AUDITED] ON [dbo].[authors] FOR UPDATE NOT FOR R
EPLICATION AS
BEGIN
PRINT 'HERE'
Declare @.mval nvarchar(256)
Declare @.mval2 nvarchar(256)
Declare @.mvalall nvarchar(512)
SELECT
@.mval = ' UPDATE: Before First Name: ' + au_fname + ' -
' + ' Last Name: ' + au_lname + ' | '
FROM DELETED
SELECT
@.mval2 = ' After First Name: ' + au_fname + ' - ' + '
Last Name: ' + au_lname + ' | '
FROM INSERTED
Set @.mvalall=@.mval + @.mval2
EXEC sp_trace_generateevent
@.event_class = 82, @.userinfo=@.mvalall
ENDYmerejtrebor wrote:
> Problem: I only get one record of before and after data when performing
> multirow updates from a single update statement. I want to get before and
> after data for ALL updated records from the update statement. How can I d
o
> this? I am using sp_trace_generateevent to capture before and after data
in
> a trace when performing updates using the following code:
> CREATE TRIGGER [AUDITED] ON [dbo].[authors] FOR UPDATE NOT FOR
REPLICATION AS
> BEGIN
> PRINT 'HERE'
> Declare @.mval nvarchar(256)
> Declare @.mval2 nvarchar(256)
> Declare @.mvalall nvarchar(512)
> SELECT
> @.mval = ' UPDATE: Before First Name: ' + au_fname + '
-
> ' + ' Last Name: ' + au_lname + ' | '
> FROM DELETED
> SELECT
> @.mval2 = ' After First Name: ' + au_fname + ' - ' + '
> Last Name: ' + au_lname + ' | '
> FROM INSERTED
> Set @.mvalall=@.mval + @.mval2
> EXEC sp_trace_generateevent
> @.event_class = 82, @.userinfo=@.mvalall
> END
How about inserting direct to a table. This example assumes no nullable
columns are involved and that the key is key_col:
CREATE TRIGGER [AUDITED] ON [dbo].[authors] FOR UPDATE NOT FOR
REPLICATION AS
BEGIN
INSERT INTO tracetable
(before_au_fname, before_au_lname, after_au_fname, after_au_lname)
SELECT D.au_fname, D.au_lname, I.au_fname, I.au_lname
FROM Inserted AS I
JOIN Deleted AS D
ON I.key_col = D.key_col
WHERE I.au_fname<>D.au_fname
OR I.au_lname<>D.au_lname ;
END
David Portas, SQL Server MVP
Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.
SQL Server Books Online:
http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
--|||> How about inserting direct to a table. This example assumes no nullable
> columns are involved and that the key is key_col:
And also assumes that the primary key value is not changed. I don't think
there is a way to correlate the before/after values for a multi-row update
in that case but one could perform a FULL OUTER JOIN instead of an INNER
JOIN to make sure all changes are recorded (but will NULL before or after
values).
Hope this helps.
Dan Guzman
SQL Server MVP
"David Portas" <REMOVE_BEFORE_REPLYING_dportas@.acm.org> wrote in message
news:1161383771.558910.172880@.i42g2000cwa.googlegroups.com...
> Ymerejtrebor wrote:
>
> How about inserting direct to a table. This example assumes no nullable
> columns are involved and that the key is key_col:
> CREATE TRIGGER [AUDITED] ON [dbo].[authors] FOR UPDATE NOT FOR
> REPLICATION AS
> BEGIN
> INSERT INTO tracetable
> (before_au_fname, before_au_lname, after_au_fname, after_au_lname)
> SELECT D.au_fname, D.au_lname, I.au_fname, I.au_lname
> FROM Inserted AS I
> JOIN Deleted AS D
> ON I.key_col = D.key_col
> WHERE I.au_fname<>D.au_fname
> OR I.au_lname<>D.au_lname ;
> END
> --
> David Portas, SQL Server MVP
> Whenever possible please post enough code to reproduce your problem.
> Including CREATE TABLE and INSERT statements usually helps.
> State what version of SQL Server you are using and specify the content
> of any error messages.
> SQL Server Books Online:
> http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
> --
>|||Often, the quality of the responses received is related to our ability to
'bounce' ideas off of each other. In the future, to make it easier for us to
give you ideas, and to prevent folks from wasting time on already answered
questions, please:
Don't post to multiple newsgroups. Choose the one that best fits your
question and post there. Only post to another newsgroup if you get no answer
in a day or two (or if you accidentally posted to the wrong newsgroup -and
you indicate that you've already posted elsewhere).
If you really think that a question belongs into more than one newsgroup,
then use your newsreader's capability of multi-posting, i.e., posting one
occurrence of a message into several newsgroups at once. If you multi-post
appropriately, answers 'should' appear in all the newsgroups. Folks
responding in different newsgroups will see responses from each other, even
if the responses were posted in a different newsgroup.
Arnie Rowland, Ph.D.
Westwood Consulting, Inc
Most good judgment comes from experience.
Most experience comes from bad judgment.
- Anonymous
You can't help someone get up a hill without getting a little closer to the
top yourself.
- H. Norman Schwarzkopf
"Ymerejtrebor" <Ymerejtrebor@.discussions.microsoft.com> wrote in message
news:B05C6CDD-C085-462C-98C0-1202A26F48CF@.microsoft.com...
> Problem: I only get one record of before and after data when performing
> multirow updates from a single update statement. I want to get before and
> after data for ALL updated records from the update statement. How can I
> do
> this? I am using sp_trace_generateevent to capture before and after data
> in
> a trace when performing updates using the following code:
> CREATE TRIGGER [AUDITED] ON [dbo].[authors] FOR UPDATE NOT FOR
REPLICATION
> AS
> BEGIN
> PRINT 'HERE'
> Declare @.mval nvarchar(256)
> Declare @.mval2 nvarchar(256)
> Declare @.mvalall nvarchar(512)
> SELECT
> @.mval = ' UPDATE: Before First Name: ' + au_fname + ' -
> ' + ' Last Name: ' + au_lname + ' | '
> FROM DELETED
> SELECT
> @.mval2 = ' After First Name: ' + au_fname + ' - ' + '
> Last Name: ' + au_lname + ' | '
> FROM INSERTED
> Set @.mvalall=@.mval + @.mval2
> EXEC sp_trace_generateevent
> @.event_class = 82, @.userinfo=@.mvalall
> END
>|||Dan Guzman wrote:
> And also assumes that the primary key value is not changed. I don't think
> there is a way to correlate the before/after values for a multi-row update
> in that case but one could perform a FULL OUTER JOIN instead of an INNER
> JOIN to make sure all changes are recorded (but will NULL before or after
> values).
>
Unless there is a key value (not necessarily the primary key) that
remains unchanged then it isn't possible to correlate row values before
and after the update. That is logical enough. Rows are identifiable
only by their keys so it is all but meaningless to talk of a row
changing its key value.
Some DBMSs do allow the before and after values to be correlated
without a key. Oracle for example has a FOR EACH ROW trigger that does
exactly that. An unfortunate side effect may be that the end result
depends on some internal physical state that isn't fully exposed
anywhere in the logical model. The real solution is to ensure that
every update operation preserves enough information to make the logical
meaning explicit. If you do that then key change should not be any
problem at all.
David Portas, SQL Server MVP
Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.
SQL Server Books Online:
http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
--