Loop for updating rows with a condition - sql

I have 2 bit columns in a table active and suspended
The active column already contains values but the suspended column still null
How can I fill the suspended field with values that is opposite of active?
I was stuck in this code..
Declare #suspended bit;
--some conditions
Update Users_mock
Set Suspended = #Suspended;

A simple case statement should work:
Update userM
Set suspend = case active when 0 then 1 else 0 end

You may check this Update sql bit field in database.
It says, **Bits in SQL Server are always stored as 1 or 0 in a bitmap. **
You may use a where, if-else or case to update the column.

select abs(CONVERT(int,#suspended)-1)

Try this:
update Users_mock
set Suspended = case when active=1 THEN 0
else 1
end

Please try:
Update Users_mock
Set Suspended = 1-Active;

Related

SQL Update if null add 1 otherwise add 1 to current value

I have a query that is updating a field in my table. It could be the case that that column to be updated can be NULL if that's the case i'd like to add 1 to that cell. Otherwise i'd like to add 1 to the current value of that field.
UPDATE SET Scheduled = Scheduled + 1
Would work except when cell's have NULL as their value, it does not add the 1 value.
You can use this.
UPDATE table SET Scheduled = ISNULL(Scheduled,0) + 1
You could use CASE expression:
UPDATE table_name
SET Scheduled = CASE WHEN Scheduled IS NULL THEN 1
ELSE Scheduled + 1
END
WHERE ...;
Although you can easily do this in the update:
update t
set scheduled = coalesce(scheduled + 1, 1)
where . . .;
I would suggest removing the need for it, by defaulting the value to 0. I suspect that will make sense in your context. If you have data in the table:
update t
set scheduled = 0
where scheduled is null;
alter table t alter scheduled int not null default 0;
(Note: You can also use with values in the alter, but the update clearly shows the intent.)
Update yourTable set yourColumn=(coalesce(yourColumn,0)+1)
Or you can use
Update yourTable set yourColumn=(nullif(yourColumn,0)+1)

Need to wait on specific column state change in SQL

I need to check for the status change of a certain column in the table
I can do it using while loop, where i can get the column value and check the value and break from the loop if value is changed.
i am using SQL server 2008.
is there a better way?
Here is the sample sql query
declare #status int = 1
select #status = status from MyTable with (nolock) where Id = 100034
while #status <> 3
begin
WAITFOR DELAY '00:01'
select #status = status from MyTable with (nolock) where Id = 100034
end
Have you considered to use a trigger instead of an stored procedure? This is exactly, what are triggers for.
CREATE TRIGGER reactOnStatus3
ON MyTable
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
IF Status = 3
EXEC DoTheMagicStoredProcedure;
END;

Check how many changes were made by UPDATE

I have infinite loop in which I update whole values from one column with select-generated column. I want to break the loop when number of changes in update is 0. Update returns number of rows so what I need is to compare before update and after update column.
I think you are looking for something like this :-
WHILE(1)
BEGIN
-- Some logic here ---
UPDATE HumanResources.Employee
SET JobTitle = N'Executive'
WHERE NationalIDNumber = 123456789
IF ##ROWCOUNT = 0
BREAK
END
You can use ##ROWCOUNT to get the number of rows that were affected by UPDATE. You can get the number of rows that were actually different by providing the UPDATE clause with a WHERE clause which excludes the rows that do not need to change. For example:
UPDATE Tbl1
SET col1 = col2
WHERE col1 != col2
IF ( ##RowCount == 0) BREAK

SQl trigger after insert issue

I am working on triggers using SQL server 2005. I have a trigger for a table which is after update. After declaring the variables, the code is like this.
if #isconfirmed_before = 0 and #isconfirmed_after = 1
begin
if #invite_userid <> ''
begin
select #points = points from dbo.InvitePoint where code = 'USR' and packageid = #packageid
INSERT INTO InviteCount
([userID]
,[joinMerchantID]
,[packageID]
,[points]
,[joinDate])
VALUES
(#invite_userid
,#merchantid
,#packageid
,#points
,getdate())
end
SET #alpha_numeric=''
SELECT #alpha_numeric=#alpha_numeric+CHAR(n) FROM
(
SELECT TOP 8 number AS n FROM master..spt_values
WHERE TYPE='p' and (number between 48 and 57 or number between 65 and 90)
ORDER BY NEWID()
) AS t
update merchant
set reg_code = #alpha_numeric
where merchantid = #merchantid
END
The last part of
update merchant
set reg_code = #alpha_numeric
where merchantid = #merchantid
This reg_code shoule be inserted only once when the row is inserted but it is changing every time there is an update to the table. How do i make it happen. Please help me, Thank you in advance!!
update merchant
set reg_code = #alpha_numeric
where merchantid = #merchantid
That code is executing every time there is an update, because you have no conditional flow preventing it from executing sometimes. If you want to only execute that given a certain condition, you'll need to wrap it in an IF block.
You say: "This reg_code shoule be inserted only once when the row is inserted but it is changing every time there is an update to the table." Why is that in an AFTER UPDATE trigger then? It looks like it should be in an AFTER INSERT trigger. Unless I am misunderstanding you.
OK you are very much in trouble with triggers. First you need to show the actual create trigger code. I suspect you don't have it set correctly to only fire on insert.
Next you need to assume that the trigger must be able to handle multiple record inserts. Anytime you are setting a value to a scalar variable in a trigger, you are probably doing something wrong. This can't be your whole trigger either because you haven't shown how you get the varible values.

if-else condition for update a table in a stored procedure in SQL Server 2005

I want to update some data in a specified case, else these columns are not to be updated.
What can I write code in a stored procedure for this?
You can use a case to control whether you assign a new value or keep the old value.
update <sometable>
set field = case when <condition> then <newvalue> else field end
where <condition>
Example:
update questions
set reply = case when #input is not null then #input else reply end
where answer = 42
Use Case statement in Update clause
like
SQL Statement #6
UPDATE titles
SET price =
CASE
WHEN (price < 5.0 AND ytd_sales > 999.99)
THEN price * 1.25
WHEN (price < 5.0 AND ytd_sales < 1000.00)
THEN price * 1.15
WHEN (price > 4.99 AND ytd_sales > 999.99)
THEN price * 1.2
ELSE price
END
Taken from SQL SERVER UPDATE
Also you can go with if..else statement
If you would have been in SQL SERVER 2008, you could have avail the flavor of MERGE statement
Just an example:
IF #a <= 0
BEGIN
UPDATE table SET counter = #a, name = 'Minati'
END
ELSE
BEGIN
UPDATE table SET name = 'Minati'
END
May be you can build the condition in the update command and easily run more than one update with the diferent conditions. It may not be the most elegant way but it is prety eficient. It depends of your needs.
UPDATE table SET field=value WHERE <<condition>>
UPDATE table SET field=value2 WHERE <<condition2>>