Selecting rows based on a SQL Server "bit" column - sql

In a SQL Server table, I have a BIT column and based its value, I need to update that table's other columns with some values. I tried this
UPDATE tablename SET Completed = GETDATE() WHERE CheckTaskAvailable = TRUE
but I get the error
Msg 207, Level 16, State 1, Server SQLDEV01, Line 1
Invalid column name 'TRUE'.
How to do this in a T-SQL query?

if you want to set as true try
Update table set columnName = 1 where ...
if you want to set as false try
Update table set columnName = 0 where ...

In addition to using the values 0 and 1, the T-SQL documentation for bit says that
The string values TRUE and FALSE can be converted to bit values: TRUE is converted to 1 and FALSE is converted to 0.
so these work, too:
UPDATE tablename SET bitcolumn = 'TRUE' WHERE ...
UPDATE tablename SET othercolumn = 'something' WHERE bitcolumn = 'TRUE'

I had a need to do something similar where I was looking to update a field based on whether a record existed or not existed in another table so I used above code (thank you RezaRahmati) and added:
Update table set columnName = 1 where ID IN (SELECT ID FROM other table)
or for false
Update table set columnName = 0 where ID NOT IN (SELECT ID FROM other table)
I really enjoy Stack Overflow it has really helped me learn.

Related

Get last updated column from an update action in SQL Server

UPDATE sms.customerOtp
SET validateCounts = validateCounts + 1
WHERE customerID = '123'
After this update I need to run a select statement that should return the last updated value of validateCounts.
Is there any functions similar to SCOPE_IDENTITY to get the last updated value of a non-identity column?
You can use the OUTPUT clause:
UPDATE sms.customerOtp
OUTPUT validateCounts
SET validateCounts = validateCounts + 1
WHERE customerID = 123;
Normally, I would put the result into a table variable, but you can use it without a table variable.

How to Update a column Before Select?

I am setting a stored procedure for select and I want to update the value of one column in the database Before doing the Select.
This is what I tried but it's not working.
#roleID int and #query varchar(240)
SELECT
EP.Equipe_Projet_Id AS PROJET_ID,
U.USR_ID,
CleRepartition = CASE
WHEN #RoleID = 1 AND #query IS NOT NULL
THEN 100
AND (UPDATE EQUIPE_PROJET SET CleRepartition = 100
WHERE EP.Equipe_Projet_Id = #PROJET_ID AND EP.Role_Id = 3)
ELSE NULL
END
FROM
[EQUIPE_PROJET] EP
Expecting update of column on database and having it's value
i want to update the value of Column CleRepartition in the database while selecting.
This is not possible in a SELECT query. A SELECT retrieves data from the database. An UPDATE modifies data. These are two separate statements and cannot be combined.
You are doing this work in a stored procedure. Within a stored procedure, you can run an UPDATE and SELECT in any order, so you can accomplish both tasks. If you are concerned about data changing in the database between the two statements, you can wrap them in a transaction.
Stored procedure can do update then select after.
So I added the query of update in the beginning, then I do the select.
Like this:
UPDATE EP
SET CleRepartition = CASE
WHEN #RoleID = 1 AND #query IS NOT NULL
THEN 100
AND (UPDATE EQUIPE_PROJET
SET CleRepartition = 100
WHERE EP.Equipe_Projet_Id = #PROJET_ID
AND EP.Role_Id = 3)
ELSE NULL
END
FROM [EQUIPE_PROJET] EP
SELECT
EP.Equipe_Projet_Id AS PROJET_ID,
U.USR_ID,
CleRepartition
FROM
[EQUIPE_PROJET] EP
I hope that this will help someone.

How can I update various sql columns based on another column of the same row?

I am running SQL Server and am needing to update hundreds of entries. Column A has unique values and based on that I need to update column B of the same table, all with different values. Essentially I am looking for a way to perform the following but in a bulk manner:
UPDATE table
set column B = 'value'
where column A = 'unique value'
Is this what you are expecting,
UPDATE table
set column B = case when column A = 5 then 'unique string' end;
How about:
update table set
columnB = concat('unique ', columnA)
you may, or may not, need a where clause, depending on your needs.
With hundreds of values you better have the {unique value - update value} mapping defined in a separate table as TT is asking. But otherwise, if you are okay with hard-coding those mappings in your UPDATE statement:
UPDATE t
SET B = CASE A
WHEN 'unique value1' THEN 'value1'
WHEN 'unique value2' THEN 'value2'
WHEN 'unique value3' THEN 'value3'
ELSE 'Unknown'
END
FROM table t
BTW, the above is only for 3 mappings
Here, you need to write cursor to update a column value in the same table
BEGIN
DECLARE c_a, c_b TEXT;
DECLARE c_ab CURSOR FOR
SELECT column_a,column_b FROM c_table;
OPEN c_ab;
LOOP
FETCH c_ab into c_ca, c_cb;
IF c_ca = "0" THEN
update c_table SET column_b = "No" WHERE
column_a = c_ca;
END IF;
IF c_ca = "1" THEN
update c_table SET column_b = "Yes" WHERE
column_a = c_ca;
END IF;
END LOOP;
CLOSE c_ab;
END
Working and tested code [please refer some cursor tutorials to update according to your condition] and with this you can update table in bulk and speedy
Thanks #Jim Macaulay. That did it. Thank you everyone else for your input.

updating a field where field cannot be less than zero

im using the following query to update my field
UPDATE tableName SET fieldName = fieldName-10
WHERE id=1;
and this is working fine in my case but i want that if the result is less than zero than query should not execute.
i've tried this
UPDATE tableName SET fieldname = fieldName-10
WHERE id=1 and fieldName>0;
but it returns with an error syntax error in your UPDATE statement.
thanx in advance
did you mean this? if pqty is the field of your table.
UPDATE tableName SET fieldname = pqty-10 WHERE id=1 and pqty>10;

IF UPDATE() in SQL server trigger

If there's:
IF UPDATE (col1)
...in the SQL server trigger on a table, does it return true only if col1 has been changed or been updated?
I have a regular update query like
UPDATE table-name
SET col1 = 'x',
col2 = 'y'
WHERE id = 999
Now what my concern is if the "col1" was 'x' previously then again we updated it to 'x'
would IF UPDATE ("col1") trigger return True or not?
I am facing this problem as my save query is generic for all columns, but when I add this condition it returns True even if it's not changed...So I am concerned what to do in this case if I want to add condition like that?
It returns true if a column was updated. An update means that the query has SET the value of the column. Whether the previous value was the same as the new value is largely irelevant.
UPDATE table SET col = col
it's an update.
UPDATE table SET col = 99
when the col already had value 99 also it's an update.
Within the trigger, you have access to two internal tables that may help. The 'inserted' table includes the new version of each affected row, The 'deleted' table includes the original version of each row. You can compare the values in these tables to see if your field value was actually changed.
Here's a quick way to scan the rows to see if ANY column changed before deciding to run the contents of a trigger. This can be useful for example when you want to write a history record, but you don't want to do it if nothing really changed.
We use this all the time in ETL importing processes where we may re-import data but if nothing really changed in the source file we don't want to create a new history record.
CREATE TRIGGER [dbo].[TR_my_table_create_history]
ON [dbo].[my_table] FOR UPDATE AS
BEGIN
--
-- Insert the old data row if any column data changed
--
INSERT INTO [my_table_history]
SELECT d.*
FROM deleted d
INNER JOIN inserted i ON i.[id] = d.[id]
--
-- Use INTERSECT to see if anything REALLY changed
--
WHERE NOT EXISTS( SELECT i.* INTERSECT SELECT d.* )
END
Note that this particular trigger assumes that your source table (the one triggering the trigger) and the history table have identical column layouts.
What you do is check for different values in the inserted and deleted tables rather than use updated() (Don't forget to account for nulls). Or you could stop doing unneeded updates.
Trigger:
CREATE TRIGGER boo ON status2 FOR UPDATE AS
IF UPDATE (id)
BEGIN
SELECT 'DETECT';
END;
Usage:
UPDATE status2 SET name = 'K' WHERE name= 'T' --no action
UPDATE status2 SET name = 'T' ,id= 8 WHERE name= 'K' --detect
To shortcut the "No actual update" case, you need also check at the beginning whether your query affected any rows at all:
set nocount on; -- this must be the first statement!
if not exists (select 1 from inserted) and not exists (select 1 from deleted)
return;
SET NOCOUNT ON;
declare #countTemp int
select #countTemp = Count (*) from (
select City,PostCode,Street,CountryId,Address1 from Deleted
union
select City,PostCode,Street,CountryId,Address1 from Inserted
) tempTable
IF ( #countTemp > 1 )
Begin
-- Your Code goes Here
End
-- if any of these "City,PostCode,Street,CountryId,Address1" got updated then trigger
-- will work in " IF ( #countTemp > 1 ) " Code)
This worked for me
DECLARE #LongDescDirty bit = 0
Declare #old varchar(4000) = (SELECT LongDescription from deleted)
Declare #new varchar(4000) = (SELECT LongDescription from inserted)
if (#old <> #new)
BEGIN
SET #LongDescDirty = 1
END
Update table
Set LongDescUpdated = #LongDescUpdated
.....