Append column's data to another column in SQL Server - sql

I want to append everything in Field1 to Field2 and then make Field1 values NULL for all records in the table. I do not want to merge these fields into a single field, I still want both fields to remain.
Take the following example:
Field 1 Field 2
Test Value NULL
NULL Another Value
My Value Current Value
I want to end up with:
Field 1 Field 2
NULL Test Value
NULL Another Value
NULL Current ValueMyValue
Thanks in advance!

How about:
UPDATE table
SET Field2 = isnull(Field2,'') + isnull(Field1,''), Field1 = NULL
What I would suggest if you are not sure about it is to wrap the update in a BEGIN TRAN, ROLLBACK like so:
BEGIN TRAN
SELECT * FROM thistable
UPDATE thistable
SET Field2 = isnull(Field2,'') + isnull(Field1,'')
, Field1 = NULL
SELECT * FROM thistable
ROLLBACK
That way you will get a view of what the query will do before it makes the change 'permanent'. Once you are happy change ROLLBACK to COMMIT and run again.
VIEW DEMO HERE

How about:
UPDATE MyTable
SET Field2 = ISNULL(Field2, '') + ISNULL(Field1, '')
To join the values into Field2.
And
UPDATE MyTable
SET Field1 = NULL
To clear out Field1 once you are sure the first script worked.

How about a little something like this:
UPDATE <Table name> SET field_2 = CONCAT(field_2, field_1);
UPDATE <Table name> SET field_1 = NULL;

Related

Populate extra database column depending on other column values

I have a database which collects data from an application. And now, I have to create another column that will be populated with predefined data depending on the values in other columns. So, no math, just to look up the values in two other columns and insert the data into the newly added column.
Example
id column1 column2 newColumn
1 15 3 100
So when column1 has 15, and column2 has 3, the newColumn should be auto-populated with 100. Again, the number 100 is predifned, not calcualted.
I know I can use triggers for new entries, but the database already has a large amount of data entered, so is there a way to auto populate the newColumn for data that is already tere?
EDIT --------------------------------
So I can use update to populate the column for the records that are already entered ?!
Can i make a trigger which will wait for both values and until both are entered it will return NULL?
You can create scalar function:
ALTER FUNCTION [dbo].[Test] ( #column1 INT, #column2 INT)
RETURNS INT
WITH SCHEMABINDING
AS
BEGIN
DECLARE #r INT
IF #column1 = 15 AND #column2 = 3
SET #r = 100
ELSE
SET #r = NULL
RETURN #r
END
And then add new computed column:
ALTER TABLE TableName ADD ColumnName AS dbo.Test(column1, column2) PERSISTED
Persisted means, that column is not calculated on the fly, but data is saved.
That's why you used WITH SCHEMABINDING. Without binding you can not make the column persisted.
You can also update your current data with simple update statement like in #Rhys Jones answer and add trigger on table like:
ALTER TRIGGER trTest ON TableName
AFTER INSERT, UPDATE
AS
BEGIN
IF UPDATE(column1) AND UPDATE(column2)
BEGIN
UPDATE TableName
SET NewColumn = CASE
WHEN column1 = 15 and column2 = 3 then 100
ELSE NULL
END
FROM Inserted i
JOIN TableName t ON t.id = i.id
END
END
You could just use a single UPDATE to update the missing values, then use the TRIGGER for new rows.
update MyTable set
newColumn = case
when column1 = 15 and column2 = 3 then 100
when ...
end
where
newColumn is null
However, note what #jarlh says above, there are usually better ways of doing this such as views or computed columns.

PL-SQL manipulate column and insert

I added new column to my existing table, my aim to insert data to the new column with using existing column's data after some manipulation, such as adding prefix. the new and existing column's type is string.
How can I perform it ?
I have no idea about plsql. SQL is enough for this situation?
I haven't got PL/SQL here, so I can't test it but it should be easy.
Let's start by altering the table:
ALTER TABLE table_name
ADD new_column varchar2(50);
Then, let's update it.
We'll start by adding all the values from the old_column that don't begin with the prefix.
UPDATE table_name t1
SET t1.new_column = 'prefix' || t1.old_column
WHERE t1.old_column NOT LIKE 'prefix%';
Then, we can simply copy the values from the old_column that already have the prefix
UPDATE table_name t1
SET t1.new_column = t1.old_column
WHERE t1.old_column LIKE 'prefix%';
Just update all records in a table.
It's possible to do it in single run through all records:
update existing_table
set
newcolumn = case
when (length(oldcolumn) = 13) and (oldcolumn like '+%')
then oldcolumn
when (length(oldcolumn) = 12) and (oldcolumn like '90%')
then '+' || oldcolumn
when (length(oldcolumn) = 10) and not (oldcolumn like '+%')
then '+90' || oldcolumn
else '?'
end
After update it's possible to check for invalid conversions:
select oldcolumn, newcolumn
from existing_table
where newcolumn = '?'
and correct case conditions or update remaining records one by one.

Whats Select '1' for in the following stored proceedure

BEGIN
IF EXISTS(SELECT * FROM Table1 WHERE ID=#ID)
BEGIN
UPDATE Table1 SET Name=#Name WHERE ID=#ID
SELECT '1'
END
ELSE
SELECT '0'
END
Is this the row no. of the table or what ?
Also "IF EXISTS" is checking what ? the table or if the ID exists or not ??
It looks like whoever wrote that Stored Procedure is using that as a return value to indicate success or failure.
Doing things that way will result in a single row with a single column being returned for each call to the procedure.
The correct way to handle this would be to actually use the return value of the stored procedure, rather than returning the single column single row:
BEGIN
IF EXISTS(SELECT * FORM Table1 WHERE ID = #ID)
BEGIN
UPDATE Table1 SET Name = #Name WHERE ID = #ID
RETURN 1
END
RETURN 0
END
The IF EXISTS is checking if there is a row in Table1 with the given ID. If there is a row it will update that row with the given name. The Select "1" will return "1" and Select "0" returns "0". The "1" or "0" would indicate if the row was found or not.
Presumably some calling code checks this value to determine if a row was updated or not.
Rather than checking and updating (two table accesses) you might as well do this.
UPDATE Table1 SET Name=#Name WHERE ID=#ID
SELECT CASE WHEN ##Rowcount = 0 THEN 0 ELSE 1 END
If id is the PK then you can just do
UPDATE Table1 SET Name=#Name WHERE ID=#ID
SELECT ##Rowcount
Note as long as SET NOCOUNT is not on then the number of rows affected will get passed back to the client application anyway.
Select '1' is used to indicate that Table1 contains the id value #ID (a parameter) was updated. Select '0' indicates that Table1 does not contain the id value #ID.

SQL update query

I want to update two fields in one sql query. How do I do that?
update tablename set field1= val1 where id=1
Now I want to update 2 fields as follows: How can I do that?
update tablename set field1 =val1 and set field2=val2 where id=1
Your syntax is almost correct, but you can't use AND.
UPDATE tablename SET field1=var1, field2=var2 WHERE id=1
Or to be safe, I like to write UPDATE statements like this:
UPDATE T
SET
T.Field1 = Value1
,T.Field2 = Value2
-- SELECT *
FROM TableName AS T
WHERE T.ID = 1
This way you can be sure of what you'll be updating.
UPDATE TableName
SET Field1=Value1
,Field2=Value2
WHERE id=id_value
Like the others, but this is how I like to indent and format it, on bigger complex queries, proper formating matters alot!
You almost had it:
update tablename
set field1=val1,
field2=val2
where id=1
UPDATE tablename SET field1 = var1, field2 = var2 WHERE id = 1;
COMMIT;

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
.....