SQL Server: copy, replace and paste within same table - sql

I am pretty new to SQL and hope someone can help me with the following general question.
I have a large table with several columns where I want to do 3 things via one stored procedure:
Select all data for country Great Britain (GB), e.g. by using something like the following:
SELECT *
FROM XYZ_TableData
WHERE (countryCode LIKE 'GB')
Copy all the above to a temp table and replace 'GB' in column countryCode by 'XX'.
Copy the data from the temp table and insert it into the above table (i.e. with the copied data showing XX instead of GB).
Can anyone help me to get a start here?

Do it all in one step, no temp table required:
insert into mytable(field1,field2,field3,country)
select field1,field2,field3,'XX' As Country from mytable where country='GB'
This assumes you are trying to append a new set of records to the table, not update the pre-existing records. I read the question one way, but Theresa read it another...guess you need to decide what you meant.

Why aren't you doing an UPDATE?
UPDATE XYZ_TableData
SET countryCode = 'XX'
WHERE countryCode = 'GB'

Related

Creating a computed Int column in SQL Server from a text column

I want to create a new column in an existing SQL Server table that utilizes state abbreviations (an existing column) to recode the states into a number (1-50) for statistical analysis that will be performed after exporting the output.
Assuming that Alabama is AL = 1 and Wyoming is WY = 50, how would I go about doing this for every state?
Two ways:
Create a lookup table, STATE_ID (with values 1..50) and STATE_ABBREV ('AL' to 'WY'), then join on this table.
Create a large CASE statement:
CASE STATE_ABBR
WHEN 'AL' THEN 1
...
WHEN 'WY' THEN 50
ELSE NULL
END AS STATE_ID
Using a lookup table is really preferred, as this puts the logic into a single place in case it gets used elsewhere. Plus, this is really data, and coding it into a view as code is not the right way to go.
A different approach, if you don't want to use a temporary or lookup table. Create a list of all states in the alphabetical order, and use the charindex function as shown below
create table #temp
( stateCode char(2))
INSERT INTO #temp values ('PA'),('AL'),('NJ'),('MA'),('DC')
select StateCode,charindex(Statecode+'|','AL|PA|NJ|NY|MA|DC|')/3+1 as numb
from #temp
order by numb
Note that charindex is slow, but this approach could be adapted to your computed field if you want.
Again, I think a lookup table is a better solution, but if it has to be a computed field, this should work for you

How to populate dummy data into an existing table?

I have a large table with given number of rows in which I'd like to replace personal informations with dummy data. I've written functions for this but actually struggling with how to implement it.
I'd like to do something like:
ALTER TABLE SomeTable DROP COLUMN SomeName
ALTER TABLE SomeTable ADD COLUMN SomeName NVARCHAR(30) DEFAULT (SELECT * FROM dbo.FakeName)
Help would be appreciated.
Instead of dropping and adding a column, just do an UPDATE.
If you just want to update the actual data with dummy data , why can't you use update statement as below. We do almost similar in our day to day work. For ex. if we would like to sanitize actual email address of users while restoring the data in my local or test machine (in column SomeName) and in another column we just want to update it with 'XXX' .
UPDATE SomeTable
SET Email_address= SUBSTRING(Email_address,0,CHARINDEX('#',Email_address)) + '#mytest.com',
SomeName2= 'XXX',

CONCAT in Oracle

I've been researching the concat function extensively but hit a wall creating a temp table. I have two columns: ID (ex. 4323) and Source (ex. PHI). I want to add a column that includes a prefix of "API-" to the ID column (ex. API-4332). Anyone have any insight?
All rows?
UPDATE TheTable
SET id = 'API-'||id;
Or,
UPDATE TheTable
SET id = CONCAT('API-',id);
EDIT:
Your problem statement led me to believe you wanted to create a new column ("I want to add a column..."). Sorry for the confusion. I have changed the answer to update the ID column.

How to Update a Single record despite multiple Occurances of the same ID Number?

I have a table that looks like the below table:
Every time the user loan a book a new record is inserted.
The data in this table is derived or taken from another table which has no dates.
I need to update this tables based on the records in the other table: Meaning I only need to update this table based on what changes.
Example: Lets say the user return the book Starship Troopers and the book return is indicated to Yes.
How do I update just that column?
What I have tried:
I tried using the MERGE Statement but it works only with unique rows of data, meaning you get an error if the same ID appears more than once.
I also tried using a basic UPDATE Statement and a JOIN but that's not going well.
I am asking because I have ran out of ideas.
Thanks for reading
If you need to update BooksReturn in target table based on the same column in source table
UPDATE t
SET t.booksreturn = s.booksreturn
FROM target t JOIN source s
ON t.userid = s.userid
AND t.booksloaned = s.booksloaned
Here is SQLFiddle demo
You can do this by simple Update & Insert statement.....
Two table A & B
From B you want to insert data into A if not exists other wise Update that data....
,First Insert into temp table....
SELECT *
INTO #MYTEMP
FROM B
WHERE BOOKSLOANED NOT IN (SELECT BOOKSLOANED
FROM A)
,Second Check data and insert into A.
INSERT INTO A
SELECT *
FROM #MYTEMP
And at last write one simple update statement which update all data of A. If any change then it also reflect to that data otherwise data as it is.
You can also update from #MYTEMP table.

How to update column with the data from the columns in the same row in MYSQL?

I have a table house with fields price and area, now I want to add one more column named 'average_price'.
How could I set the average_price according to the price and area in MYSQL?
Just one idea:
Add your column in your favorite editor/method
Loop through your table and define average_price value
Update actual row with your value
UPDATE your_table SET average_price = price/area;
You can do it with a suquery. But I don't know about performance.
UPDATE `houses` AS h
SET `avg_price` = (
SELECT AVG(`price`)
FROM `houses` AS h2
WHERE h2.area == h.area
)
Or you could create a temporary table in which to put the average prices and then update.
This doesn't sound like the kind of data you should actually store, by how often you'd have to update it - once every single time you modify the house table in any way! That's a lot of unnecessary load on the database, and a whole lot of room for human error.
Instead, I recommend acquiring it on the fly through a SQL query when you need it, and never actually storing it.
Retrieving from all areas:
SELECT `area`, AVG(`price`) AS `average_price`
FROM `house`
GROUP BY `area`
ORDER BY `average_price` ASC
Retrieving from a specific area:
SELECT `area`, AVG(`price`) AS `average_price`
FROM `house`
WHERE `area` = "New York"
GROUP BY `area`