Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Conditional update

Author  Topic 

OldMySQLUser
Constraint Violating Yak Guru

301 Posts

Posted - 2009-07-22 : 04:52:11
I have a table

Categories
----------

ID Category
-- --------
5720 001
5720 002
5720 003
5720 004
5720 005

I need to create a script so that

1) if the table does not contain a category of 001 for ID 5720 then add it

2) delete any entries for id 5720 where the category is not 001

How can I achieve this please?

bklr
Master Smack Fu Yak Hacker

1693 Posts

Posted - 2009-07-22 : 04:57:09
declare @cnt int
select @cnt = COUNT(*) from catefories where id = '001' and category = 5720

insert into categories select '001', 5720 where @cnt = 0

delete from categories where id = 5720 and category <> '001'

Go to Top of Page

OldMySQLUser
Constraint Violating Yak Guru

301 Posts

Posted - 2009-07-22 : 05:12:58
Many thanks for your kind help.
Go to Top of Page

webfred
Master Smack Fu Yak Hacker

8781 Posts

Posted - 2009-07-22 : 05:13:00
INSERT Categories([ID], Category)
SELECT 5720, '001'
WHERE NOT EXISTS(select * from Categories where [ID]=5720 and Category='001'

DELETE as posted by bklr


No, you're never too old to Yak'n'Roll if you're too young to die.
Go to Top of Page

bklr
Master Smack Fu Yak Hacker

1693 Posts

Posted - 2009-07-22 : 05:14:41
quote:
Originally posted by OldMySQLUser

Many thanks for your kind help.



welcome
Go to Top of Page
   

- Advertisement -