How to update some part of text using SQL UPDATE statement - sql

I have a query saved in column of a table named sqlcode which is maintaining the metadata. For instance following is a query:
select
id, name, address, phone,
.......
......
, upddate
from
bank a
join
bankreg b on a.id = b.id
where
(condition)
I'm trying to update the text of query saved in metadata but I want to only update column names part of the query without making any change to select, from, joins or any other conditions. Any way of only updating column names would be helpful. I've tried using replace function but couldn't got desired output.
I want to update columns of this textual query with the columns present in master table. If new columns are added in master, I want to add them to metadata query as well which is saved in text form. INFORMATION_SCHEMA.COLUMNS gives me the column names now I just want to update these column names to above query

If you wrap the columns you need to update in brackets, you can update them in your REPLACE, without updating the items in the SELECT portion.
select
id,name,address,phone,
.......
......
,upddate
from bank a
join bankreg b
on
a.id = b.id
where ([address] = 'My Street')
Your update would then be:
UPDATE MyTable SET MyCol = REPLACE(MyCol , '[address]', '[some_other_field]')

You wanna rename names of columns in select part?
Use currentNAme AS NewName, or currentName NewName, for each name you wanna rename.
Depends on the DBMS weather one or other or both syntax are supported (sql-server -> go with AS). Test with 1 column name to see which one works then use that one till end
select
id AS myNameForId,
name AS myNmeForName,
.......
......
,upddate
from bank AS a
join bankreg AS b
on
a.id = b.id
where (condition)
OR
select
id myNameForId,
name myNmeForName,
.......
......
,upddate
from bank a
join bankreg b
on
a.id = b.id
where (condition)

Related

I need to create a VIEW from an existing TABLE and MAP an additional COLUMN to that VIEW

I am fairly new to SQL. What I am trying to do is create a view from an existing table. I also need to add a new column to the view which maps to the values of an existing column in the table.
So within the view, if the value in a field for Col_1 = A, then the value in the corresponding row for New_Col = C etc
Does this even make sense? Would I use the CASE clause? Is mapping in this way even possible?
Thanks
The best way to do this is to create a mapping or lookup table
For example consider the following LOOKUP table.
COL_A NEW_VALUE
---- -----
A C
B D
Then you can have a query like this:
SELECT A.*, LOOK.NEW_VALUE
FROM TABLEA AS A
JOIN LOOKUP AS LOOK ON A.COL_A = LOOK.COL_A
This is what DimaSUN is doing in his query too -- but in his case he is creating the table dynamically in the body of the query.
Also note, I'm using a JOIN (which is an inner join) so only results in the lookup table will be returned. This could filter the results. A LEFT JOIN there would return all data from A but some of the new columns might be null.
Generally, a view is an instance of a table/a replica provided that there is no alteration to the original table. So, as per your query you can manipulate the data and columns in a view by using case.
Create View viewname as
Select *,
case when column=a.value then 'C'
....
ELSE
END
FROM ( Select * from table) a
If You have restricted list of replaced values You may hardcode that list in query
select T.*,map.New_Col
from ExistingTable T
left join (
values
('A','C')
,('B','D')
) map (Col_1,New_Col) on map.Col_1 = T.Col_1
In this sample You hardcode 'A' -> 'C' and 'B' -> 'D'
In general case You better may to use additional table ( see Hogan answer )

I want to use select query in the update query statement

I have changed three columns by using a replace command in sql server with following query
select name ,replace (name,'...','.') as names from dbo.emp_2 where name like '%..%'
After replacing the replaced values has been entered in a new row .
Now i just wants to update the replaced values into original table . SO, I was thinking to use select query in the update query .
Is that possible , Is it so kindly provide a sample query for that
Try something like this
Update dbo.emp_2
set name =replace (name,'...','.') where name like '%..%'
Update dbo.emp_2
Set name = replace (name,'...','.')
Where name like '%..%'
You can do:
UPDATE TableA
SET Column1 = 'Test' + Column1
You can even make joins in your update query
UPDATE A
SET A.Column1 = 'Test' + B.Column2
FROM TableA A
INNER JOIN TableB B
ON B.B_Id = A.A_Id

update multiple fields SQL

Hi my problem is I want to update a field in 1 table using another field from several tables dependant upon where the item originates my only problem is the table which im trying to update has several of the same values in so am getting 'single row sub-query returns more than 1 row'. I dont mind all of the updated fields with the same value being the same. Heres my SQL:
update URL_SET_TAB u
Set U.ITEM_NAME = (select a.PROGRAMME_NAME
from (SELECT (nvl(nvl(b.prog_name,c.movie_name), A.URL_1)) as programme_name, a.ID, a.URL_1
FROM URL_SET_TAB a, prog_name_lookup b, movie_name_lookup c
where a.url_1 = b.url_1(+) and a.url_1 = C.MOVIE_URL(+)
) a
where u.ID = a.ID and U.URL_1 = a.URL_1
)
You need to identify a key column which when matched for URL_SET_TAB and inline view a so that the subquery returns only a single record. This is a limitaion of an UPDATE clause.
Thanks,
Aditya

Writing a single UPDATE statement that prevents duplicates

I've been trying for a few hours (probably more than I needed to) to figure out the best way to write an update sql query that will dissallow duplicates on the column I am updating.
Meaning, if TableA.ColA already has a name 'TEST1', then when I'm changing another record, then I simply can't pick a value for ColA to be 'TEST1'.
It's pretty easy to simply just separate the query into a select, and use a server layer code that would allow conditional logic:
SELECT ID, NAME FROM TABLEA WHERE NAME = 'TEST1'
IF TableA.recordcount > 0 then
UPDATE SET NAME = 'TEST1' WHERE ID = 1234
END IF
But I'm more interested to see if these two queries can be combined into a single query.
I am using Oracle to figure things out, but I'd love to see a SQL Server query as well. I figured a MERGE statement can work, but for obvious reasons you can't have the clause:
..etc.. WHEN NOT MATCHED UPDATE SET ..etc.. WHERE ID = 1234
AND you can't update a column if it's mentioned in the join (oracle limitation but not limited to SQL Server)
ALSO, I know you can put a constraint on a column that prevents duplicate values, but I'd be interested to see if there is such a query that can do this without using constraint.
Here is an example start-up attempt on my end just to see what I can come up with (explanations on it failed is not necessary):
ERROR: ORA-01732: data manipulation operation not legal on this view
UPDATE (
SELECT d.NAME, ch.NAME FROM (
SELECT 'test1' AS NAME, '2722' AS ID
FROM DUAL
) d
LEFT JOIN TABLEA a
ON UPPER(a.name) = UPPER(d.name)
)
SET a.name = 'test2'
WHERE a.name is null and a.id = d.id
I have tried merge, but just gave up thinking it's not possible. I've also considered not exists (but I'd have to be careful since I might accidentally update every other record that doesn't match a criteria)
It should be straightforward:
update personnel
set personnel_number = 'xyz'
where person_id = 1001
and not exists (select * from personnel where personnel_number = 'xyz');
If I understand correctly, you want to conditionally update a field, assuming the value is not found. The following query does this. It should work in both SQL Server and Oracle:
update table1
set name = 'Test1'
where (select count(*) from table1 where name = 'Test1') > 0 and
id = 1234

how to compare two rows in one mdb table?

I have one mdb table with the following structure:
Field1 Field2 Field3 Field4
A ...
B ...
I try to use a query to list all the different fields of row A and B in a result-set:
SELECT * From Table1
WHERE Field1 = 'A'
UNION
SELECT * From Table1
WHERE Field1 = 'B';
However this query has two problems:
it list all the fields including the
identical cells, with a large table
it gives out an error message: too
many fields defined.
How could i get around these issues?
Is it not easiest to just select all fields needed from the table, based on the Field1 value and group on the values needed?
So something like this:
SELECT field1, field2,...field195
FROM Table1
WHERE field1 = 'A' or field1 = 'B'
GROUP BY field1, field2, ....field195
This will give you all rows where field1 is A or B and there is a difference in one of the selected fields.
Oh and for the group by statement as well as the SELECT part, indeed use the previously mentioned edit mode for the query. There you can add all fields (by selecting them in the table and dragging them down) that are needed in the result, then click the 'totals' button in the ribbon to add the group by- statements for all. Then you only have to add the Where-clause and you are done.
Now that the question is more clear (you want the query to select fields instead of records based on the particular requirements), I'll have to change my answer to:
This is not possible.
(untill proven otherwise) ;)
As far as I know, a query is used to select records using for example the where clause, never used to determine which fields should be shown depending on a certain criterium.
One thing that MIGHT help in this case is to look at the database design. Are those tables correctly made?
Suppose you have 190 of those fields that are merely details of the main data. You could separate this in another table, so you have a main table and details table.
The details table could look something like:
ID ID_Main Det_desc Det_value
This way you can filter all Detail values that are equal between the two main values A and B using something like:
Select a.det_desc, a.det_value, b.det_value
(Select Det_desc, det_value
from tblDetails
where id_main = a) as A inner join
(Select Det_desc, det_value
from tblDetails
where id_main = a) as B
on A.det_desc = B.det_desc and A.det_value <> B.det_value
This you can join with your main table again if needed.
You can full join the table on itself, matching identical rows. Then you can filter on mismatches if one of the two join parts is null. For example:
select *
from (
select *
from Table1
where Field1 = 'A'
) A
full join
(
select *
from Table1
where Field1 = 'B'
) B
on A.Field2 = B.Field2
and A.Field3 = B.Field3
where A.Field1 is null
or B.Field1 is null
If you have 200 fields, ask Access to generate the column list by creating a query in design view. Switch to SQL view and copy/paste. An editor with column mode (like UltraEdit) will help create the query.