Remove from other SQL table after using the Match function? - sql-server

I found this code online and like its use for inserting data based on common column variables.
Select * from Table1
Merge into table1 as T using [table] as S
on T.[Last Name] = S.[Last Name] and T.[First Name] = S.[First Name]
When Matched then Update Set T.[DOB] = S.[DOB];
Problem is I want to get rid of the data that matched up from the source. So, once the information is has been matched and inserted into the target I want to delete the matched information from the source.

After the merge statement you can do a delete statement using inner join:
DELETE T1
FROM Table1 T1 INNER JOIN Table2 T2
ON T1.[Last Name] = T2.[Last Name] AND T1.[First Name] = T2.[Last Name];
Note: By default SQL table names are not case-sensitive, so both Table1 and table1 will refer to the same table. So please change the table
name.

Related

SQL Server : update old ID to new ID (SELF JOIN in UPDATE)

I have a SQL Server table, and column category IDs (kategori) needs to be updated.
I need to find id_old first and update as new id instead:
How can I do this in batch with a T-SQL statement?
use SELF JOIN. You need to use a different alias on the table.
UPDATE t2
SET kategori = t1.id
FROM yourtable t1
INNER JOIN yourtable t2 ON t1.id_old = t2.kategori
WHERE t2.kategory <> 0 -- not sure but you might need this condition

Update a column of a table with a column of another table in SQL Server

I am trying to update column from one table to another table of different database.
I searched on stack but found answers for PostgreSQL and SQLite. Those code ain't worked for me properly in SQL Server.
Say,
D1,D2 are the two different databases
T1 is the table
C1,C2,C3 are the columns in T1
I want to update like
UPDATE T1
SET D2.T1.C1 = D1.T1.C1
WHERE D2.T1.C2 = D1.T1.C2
Everything except the where clause works fine.
Here is some code I tried:
use DB2
GO
UPDATE TABLE1
SET COL1 = (SELECT COL1 FROM DB1.dbo.TABLE1)
WHERE COL2 = DB1.dbo.TABLE1.COL2
How shall I write this query?
Note: D1 and D2 are identical. Both have the exact same schema. Just the name and data are different. Both databases are on the same server.
SQL Server supports an update join syntax:
UPDATE t1
SET COL1 = t2.COL1
FROM TABLE1 D1.t1
INNER JOIN TABLE2 D2.t2
ON t1.COL2 = t2.COL2;
Actually, your current approach might work, but you should try changing it to this:
UPDATE TABLE1 D1.t1
SET COL1 = (SELECT t2.COL1 FROM TABLE2 D2.t2 WHERE T1.COL2 = T2.COL2);
You can simply use an INNER JOIN cause sql-server support Cross-Database Queries, so you can do as:
UPDATE T1
SET T1.Col1 = T2.Col1
FROM DataBase1.Schema.TableName T1 INNER JOIN DataBase2.Schema.TableName T2
ON T1.ID = T2.ID;
Please, visit and read Cross-Database Queries.
Or update tableName set column Name = (select columnName from second table where 1=1) i.e condition is either true or false optional though

Combining two tables with multiple common columns into one in SQL

I am trying to create a table in SQL server which has the same output as the following:
Select *
FROM Table1
LEFT JOIN Table2
ON
Table1.Key1 = Table2.Key1
AND Table1.Key2 = Table2.Key2
The result of the above query is exactly what I need, but as a new table.
The problem is, there are multiple columns that are common between the two tables. I have executed the following code:
Select *
INTO NewTable
FROM Table1
LEFT JOIN Table2
ON
Table1.Key1 = Table2.Key1
AND Table1.Key2 = Table2.Key2
The following error appears:
Msg 2705, Level 16, State 3, Line 1
Column names in each table must be unique. Column name 'Key1' in table 'NewTable' is specified more than once.
Could someone please help? I would highly appreciate it after a long day of searching the internet without any solution.
Thank you so much in advance!
This will help you identify what records you need to get a unique list.
select ',' + Column_Name
from INFORMATION_SCHEMA.COLUMNS c2
where column_Name not in (
select COLUMN_NAME
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = 'table1')
and table_Name = 'Table2'
So you can safely say:
Select table1.*
<<Paste in your results from above here>>
INTO NewTable
FROM Table1
LEFT JOIN Table2
ON
Table1.Key1 = Table2.Key1
AND Table1.Key2 = Table2.Key2
When you write select into table query then it dynamically create the table and at the time of creating a table the name of column should be unique.
In your case when you join then name of column can be in both table.
So replace * and write it as shown below
Select Column1, Column2, ... etc
INTO NewTable
FROM Table1
LEFT JOIN Table2
ON
Table1.Key1 = Table2.Key1
AND Table1.Key2 = Table2.Key2
Your easiest option would be to change your select-into statement into something like this, where you give unique names to the fields with the same name:
Select Table1.Key1 as [Key1a], Table2.Key1 as [Key1b], etc.
INTO NewTable
FROM Table1
LEFT JOIN Table2
ON
Table1.Key1 = Table2.Key1
AND Table1.Key2 = Table2.Key2
If you are using SSMS, you could highlight your query, right-click on it and select "Design in Query Editor" and it will show you the select statement as "select [all of the fields]" rather than "select *", which will probably be useful to you.

Query Using != On LEFT JOIN Table Returns No Result

I am querying a Microsoft SQL Server 2012.
The primary table (T1) structure contains account details:
AccountID, Name, Address
This table is dropped and recreated using external data nightly. We need to display this information but also need to exclude some of the records. Since we have no access to the external data we can't just add a column.
So we created a table (T2) to mark all the accounts we would like to exclude. It just has 2 fields:
AccountNo, Type
So we populated T2 and for every account we wanted to exclude from the display we gave the Type field a value of 'ex' (for exclude). We have no entries for the account we want to display.
When I execute the following query:
select T1.AccountID as acct, T1.Name as name, T1.Address as add
from T1
left join T2 on T1.AccountID = T2.AccountNo
WHERE T2.Type != 'ex'
The above query returns and empty set.
If I run a query to look for the value 'ex' (remove the !):
select T1.AccountID as acct, T1.Name as name, T1.Address as add
from T1
left join T2 on T1.AccountID = T2.AccountNo
WHERE T2.Type = 'ex'
The query returns the rows with that field populated with 'ex', as you expect.
I can search for NULL or NOT null with success but we need to use this extra table to do some other data manipulation in the future. In other words, we will not just be populating this field with "ex".
I'm wondering why I can't query the field in the joined table by looking for a Boolean false for a string. Is is because since the column doesn't exist in the table that is joined (T2) that it doesn't actually exist in the data set?
If that's the case how would I execute a query to return the records that do not equal a value in the joined table, whether that record exists in the joined table or not.
You can use the ISNULL solution like mentioned in the comments.
Another way you could write the query is this:
SELECT #t1.AccountID AS acct, #t1.Name AS [name], #t1.Address AS [add]
FROM #t1
LEFT JOIN #t2 ON #t1.AccountID = #t2.AccountNo
AND #t2.type = 'ex' --In case you add additional types to #t2
WHERE #t2.AccountNo IS NULL;

Updating column with value from other table, can't use distinct function

My original data is in Table2. I created Table1 from scratch. I populated Column A like this:
INSERT INTO Table1("item")
SELECT DISTINCT(Table2."item")
FROM Table2
I populated Table1.Totals (Column B) like this:
UPDATE Table1
SET totals = t2.q
FROM Table1 INNER JOIN
(
SELECT t2."item"
, SUM(t2.quantity) AS q
FROM t2
GROUP BY t2."item"
) AS t2
ON Table1."item" = t2."item"
How can I populate Table1."date"? My UPDATE above doesn't work here because I can't use an aggregate function on a date. I was able to get the results I wanted using the following code in a separate query:
SELECT DISTINCT Table1."item"
, Table2."date"
FROM Table1 INNER JOIN Table2
ON Table1."item" = Table2."item"
ORDER BY Table1."item"
But how do I use the results of this query to SET the value of the column? I'm using SQL Server 2008.
If you can't do the insert all over again, as #Lamak suggested, then you could perform an UPDATE this way:
UPDATE t1
SET t1.Date = s.Date
FROM Table1 AS t1
INNER JOIN
(
SELECT Item, [Date] = MAX([Date]) -- or MIN()
FROM Table2
GROUP BY Item
) AS s
ON t1.Item = s.Item;
For SQL Server you coul've use a single INSERT statement:
INSERT INTO Table1(Item, Totals, [Date])
SELECT Item, SUM(Quantity), MIN([Date]) -- It could be MAX([Date])
FROM Table2
GROUP BY Item
The easiest way is to use a simple CTAS (create table as select):
select item as item, SUM(quantity) as Q, MIN(date) as d into table2
from table1
group by item
Instead of creating a table, you could create a view, using a select statement like in #Lamak's answer. That way you wouldn't have to update the new row set each time the Table2 updates.

Resources