SQL Server : updating one column and inserting if not exist - sql

I have a table TableKats that looks like this:
ID - int
Name - varchar
KatID - int
What I want to do is to update the column Name from another table, and if there is a name in the other table that doesn't exist in TableKats, it should insert it and give KatID a 0
Does anybody know a way to do that? Thanks

you can do it using MERGE, as your other table schema is not known assuming Name as the column in other table too
MERGE TableKats T
USING ( SELECT * from TableB) AS S
ON T.Name = S.Name
WHEN NOT MATCHED THEN
INSERT ( Name, KatID)
VALUES ( S.Name, 0)
WHEN MATCHED THEN
UDPATE -- Not clear what needs to be updated.

Related

Create a record in table A and assign its id to table B

I have a set of companies and for each of them, I need to generate a UUID in another table.
companies table
detail_id (currently NULL for all companies)
details table
id
uuid
date
...
I'd like to update all companies with newly created detail like this:
UPDATE companies
SET details_id =
(
INSERT INTO details
(uuid, date)
VALUES (uuid_generate_v1(), now()::date)
RETURNING id
)
But that gives me a syntax error since I can't use INSERT INTO inside UPDATE.
What is a proper way to create a row in the details table and immediately set the newly created id in the companies table?
(I am using Postgres)
You can use a data-modifying CTE:
with new_rows as (
INSERT INTO details ("uuid", "date")
VALUES (uuid_generate_v1(), current_date)
RETURNING id
)
update companies
set details_id = new_rows.id
from new_rows

Create table with other table data

Following query works but i want with 2 fields
CREATE TABLE TOTAPPS (ANUM) AS SELECT a.A# FROM APPLICANT a.
This is work that
//TOTAPPS
ANUM
--------
if i want to create with 2 fields?
//Totapps
ANUM NUMBER
---------------------------
how should i create the table? in order to get the correct out?
and the NUMBER is refer to the ANUM , for example
CREATE TABLE TOTAPPS (ANUM) AS SELECT a.A# FROM APPLICANT a,
(NUMBER) AS SELECT COUNT(*) FROM a.A#;
but it's failed to work.
Calling a column NUMBER is not correct as it is a reserved word. Assuming from your second query that you want to add to your table distinct values of a.A# and the count of these values in the table, you should try this:
CREATE TABLE TOTAPPS (ANUM, MYNUMBER) AS
SELECT a.A#, COUNT(a.A#) FROM APPLICANT a GROUP BY a.A#;

Insert data from another table based on condition, if not insert specific value PSQL

I have table A with an id column and a bunch of others. I also have table B which has an id column like table A and also another column called countries. However, not all id in table A are in table B. I want to insert a new column into table A called countries2 that basically inserts the countries from table B that corresponds to the ids in both tables. If a specific id from A does not exist in B, then it always puts in the VARCHAR 'none' into countries2.
So for example if Table A has the ids 1, 2, 3, 4 and table B looks like:
id--country
1---'foo1'
3---'foo2'
I want table A to become something like:
id--country2--other original data from table A
1---'foo1'--...
2---'none'--...
3---'foo2'--...
4---'none'--...
You need to first alter your TableA to add an extra column (i.e yourNewColumn) of type varchar/varchar2
to add the column try something like
ALTER TABLE TableA ADD COLUMN yourNewColumn varchar(10);
Then you can use something like below to update TableA
UPDATE TableA
SET yourNewColumn = ISNULL(TableB.countries, 'none')
FROM TableA
LEFT JOIN TableB ON TableA.id = TableB.id
The ISNULL function in PostgreSQL might be something like
SET yourNewColumn = CASE WHEN TableB.countries IS NULL THEN 'none' ELSE TableB.countries END

SQL query to fillter and update table

i have an employee database table with a column NAME
in the NAME field we have names of employees like this -> LI-MING (ALLEN)
this is there real first name and there English nick name in ()
i would like to know if i can swap this around in an SQL UPDATE query
FROM: LI-MING (ALLEN) TO: ALLEN (LI-MING)
the reason why i would like this is Users want to have it sort this column by nick name
Try this
UPDATE Employee
SET NAME =
SUBSTRING(name,CHARINDEX('(',name)+1,(CHARINDEX(')',name)-CHARINDEX('(',name)-1))+
' ('+SUBSTRING(name,1,CHARINDEX('(',name)-1)+')'
FROM Employee
If I were you I would create seperate colums both for name and nick name. Trying to get a string portion on the fly prevent sql server from using indexes which might be really importand from performance perspective.
So there are basicly two options:
Parse values for seperate columns every time you update or insert a new employee (via TRIGGER, application code, etc).
Or just create two calculated columns but make sure they are marked as PERSISTED.
Hope it helps!
I had worked on several project and I have done it my way to update same issue that you been through in 3 steps:
1) Create table with ID or Name field and Insert the values to the table
2) Trim the values with different functions and insert the final value to different table.
3) Update the old table with the new value
I don't say this is the only way to do thing but there might be other ways as well.
Create table #Employee(
EmployeeName varchar(200)
)
Insert into #Employee
Select 'LI-MING (ALLEN)' union all
Select 'Jio-Kio (Smith)'
Select
substring(employeename,1,patindex('%(%',employeename)-1),
--Len(substring(employeename,1,patindex('%(%',employeename)-1)),
Right(employeename,len(employeename)-(len(substring(employeename,1,patindex('%(%',employeename)))))
from #Employee
Create table #EmployeeNew(
Employeename1 varchar(200),
Employeename2 varchar(200)
)
Insert into #EmployeeNew(Employeename1, Employeename2)
Select
ltrim(rtrim(substring(employeename,1,patindex('%(%',employeename)-1))),
ltrim(rtrim(Right(Employeename,charindex('(',employeename,1)-3)))
from #Employee
Select * from #Employee
Select * from #EmployeeNew
Select cast('('+Employeename1+')'+left(employeename2,len(employeename2)-1) as varchar(200)) from #EmployeeNew
Update e
Set e.EmployeeName = cast('('+e1.Employeename1+')'+left(e1.employeename2,len(e1.employeename2)-1) as varchar(200))
from #Employee e
left outer join #EmployeeNew e1 on ltrim(rtrim(substring(e.employeename,1,patindex('%(%',e.employeename)-1))) =e1.Employeename1

SQL 'simple' query syntax error - help!

My query returns a syntax error:
Invalid object name 'table.clientinfo'.
Here is my query:
INSERT table.clientinfo (name, addr, entry, affiliate )
SELECT name, addr, entry, affiliate FROM table.clientinfo WHERE product = 5
Is the error due to the insert function not finding 'clientinfo' as it does not exist.
Can anybody give me the correct syntax to create the table first before populating it from the select function?
You want CREATE TABLE
CREATE TABLE clientinfo (
name VARCHAR(100)
addr VARCHAR(100)
entry VARCHAR(100)
affiliate VARCHAR(100)
);
with specific types/sizes for your app. You might want to indicate foriegn and primary keys, constraints etc too
In SQL Server, if you want to select and insert into a new table, use this syntax:
SELECT name, addr, entry, affiliate
INTO (new table name)
FROM [table.clientinfo]
WHERE product = 5
You need to SELECT .... INTO and you need to make sure to use proper table names.
If you table name really has a dot in it (really really bad practice!), then you MUST put that table name in square brackets: FROM [table.clientinfo]
Also, when doing SELECT .. INTO ... you cannot select from an existing table and insert into the same existing table - you need to use a new table name for your destination table.
You should use
INSERT INTO [tablename] (field1, field2, ... , fieldx)
SELECT ...
Or if you want to create the other data directly:
SELECT field1, field2, ... , fieldx
INTO newTable
FROM oldtable
WHERE ....