Query to update records from two different tables - sql

I have a query that updates table records.
UPDATE #TEMP
SET [fld_LastName] = CustomerProfile.fld_LastName
,fld_FirstName = CustomerProfile.fld_FirstName
,fld_BirthDate = CustomerProfile.fld_BirthDate
FROM [DB_1].[dbo].[tbl_Customer] AS CustomerProfile --c
WHERE CustomerProfile.fld_CustomerNo = #TEMP.fld_CustomerNo
I want to update the records when the customer is not present in:
[DB_1].[dbo].[tbl_Customer]
I would want to look up to:
[DB_2].[dbo].[tbl_Customer]
How can i do that in an SQL Query?
Thanks a lot.

This should work for you:
UPDATE B
SET [fld_LastName] = CustomerProfile.fld_LastName
,fld_FirstName = CustomerProfile.fld_FirstName
,fld_BirthDate = CustomerProfile.fld_BirthDate
FROM [DB_1].[dbo].[tbl_Customer] AS CustomerProfile INNER JOIN #TEMP B
ON CustomerProfile.fld_CustomerNo = B.fld_CustomerNo
WHERE B.[fld_LastName] IS NULL OR B.fld_FirstName IS NULL OR B.fld_BirthDate IS NULL

You can do it with one update. Something like this:
DECLARE #a TABLE (id INT, val INT)
DECLARE #b TABLE (id INT, val INT)
DECLARE #c TABLE (id INT, val INT)
INSERT #a SELECT 1,NULL UNION SELECT 2,NULL UNION SELECT 3,30
INSERT #b SELECT 1,10
INSERT #c SELECT 1,20 UNION SELECT 2,20
SELECT * FROM #a
UPDATE #a
SET val = COALESCE(b.val,c.val,a.val)
FROM #a a
LEFT JOIN
#b b ON a.id=b.id
LEFT JOIN
#c c ON a.id=c.id
SELECT * FROM #a
This assumes that you prefer NOT NULL values from DB_2 to NULL values in DB_1--if those fields are even nullable.
UPDATE #TEMP
SET fld_LastName = COALESCE(b.fld_LastName,c.fld_LastName,a.fld_LastName)
,fld_FirstName = COALESCE(b.fld_FirstName,c.fld_FirstName,a.fld_FirstName)
,fld_BirthDate = COALESCE(b.fld_BirthDate,c.fld_BirthDate,a.fld_BirthDate)
FROM #Temp a
LEFT JOIN
DB_1.dbo.tbl_Customer b ON a.fld_CustomerNo = b.fld_CustomerNo
LEFT JOIN
DB_2.dbo.tbl_Customer c ON a.fld_CustomerNo = c.fld_CustomerNo

Related

How to capture columns from joined tables using output clause?

I am updating a table called tableA by joining tableB and tableC at the same time I am capturing updated records into temp table using output clause from tableA . Now I want capture columns from table B for the updated data but output clause isn't allowing the same.
Eg:
Update SLC Set SLC.Datascrublevel = C.Datascrublevel
OUTPUT [Deleted].Systemcode,
[Deleted].Systemkey,
[Deleted].datascrublevel,
[Inserted].datascrublevel
INTO #TEMP1
FROM TABLEA SLC with(nolock)
INNER JOIN TABLEB SC ON SC.SystemCode = SLC.SystemCode
INNER JOIN TABLEC SL ON SL.SystemCode = SLC.SystemCode and SLC.SystemKey = SL.Systemkey
INNER JOIN #TEMP C ON SLC.Datascrublevel <> C.DataScrubLevel AND C.Systemcode = SLC.SystemCode and C.Systemkey = SLC.SystemKey
Now I want columns from tableB to capture into temp table using output clause. Please provide your advise if there are any alternative ways.
Just Like you have given it as [deleted].[Column Name] and [Inserted].[Column Name] add one more column as [SC].[Column Name]
Example :
IF OBJECT_ID('TempDb..#TABLEA') IS NOT NULL
DROP TABLE #TABLEA
IF OBJECT_ID('TempDb..#TABLEB') IS NOT NULL
DROP TABLE #TABLEB
IF OBJECT_ID('TempDb..#TABLEC') IS NOT NULL
DROP TABLE #TABLEC
IF OBJECT_ID('TempDb..#TABLED') IS NOT NULL
DROP TABLE #TABLED
CREATE TABLE #TABLEA
(
SeqNo INT IDENTITY(1,1),
MyDate DATE
)
CREATE TABLE #TABLEB
(
SeqNo INT IDENTITY(1,1),
FullName VARCHAR(20)
)
CREATE TABLE #TABLEC
(
SeqNo INT IDENTITY(1,1),
FullName VARCHAR(20),
MyDate DATE
)
CREATE TABLE #TABLED
(
SeqNo INT,
MyDate DATE,
FullName VARCHAR(20)
)
INSERT INTO #TABLEA
(
MyDate
)
SELECT GETDATE()
UNION
SELECT GETDATE()+1
UNION
SELECT GETDATE()-1
INSERT INTO #TABLEB
(
FullName
)
VALUES('A'),('B'),('C')
INSERT INTO #TABLEC
(
FullName
)
VALUES('A'),('B'),('C')
UPDATE C
SET MyDate = A.MyDate
OUTPUT
deleted.SeqNo,
deleted.MyDate,
B.FullName
INTO #TABLED
FROM #TABLEC C
INNER JOIN #TABLEB B
ON C.FullName = B.FullName
INNER JOIN #TABLEA A
ON A.SeqNo = B.SeqNo
SELECT * FROM #TABLED

Set column values in TableA to corresponding values from TableB if some value exist in TableC

I have a TableA that I just added two columns to, StartDate and StopDate. It also contain the column UserName.
I want to fill it with values from TableB that also has StartDate and StopDate. TableB has another column called UserId.
TableC has two columns, Id and Name.
This is what I want to do, explained with some kind of pseudocode:
for each row in TableB, where TableB.UserId exists in TableC.Id, take the corresponding row in TableA where TableA.UserName = TableC.Name and set the TableA.StartDate = TableB.StartDate & TableA.StopDate = TableB.StopDate.
I tried to create a join statement that would do it but the result was kind of embarrassing.
Help would be much appreciated.
Edit: What I have tried:
UPDATE TableA
SET STARTDATE = (
SELECT TableB.StartDate
FROM TableB
WHERE TableB.UserId = (??? what should I write here)?
And then same for StopDate
You can achieve this using the "update-from" syntax.
*I see you've already solved your question, but I'll post this as a possible alternative.
declare #TableA table (id int identity(1, 1), startDate datetime, stopDate datetime, userName varchar(20))
declare #TableB table (id int identity(1, 1), startDate datetime, stopDate datetime, userId int)
declare #TableC table (userId int, userName varchar(20))
insert into #TableA (userName)
select 'A' union all select 'B'
insert into #TableB (userId, startDate, stopDate)
select 1, '2015-01-01', '2015-01-31' union all select 2, '2015-12-01', '2015-12-31'
insert into #TableC
select 1, 'A' union all select 2, 'B'
update
A
set
A.startDate = B.startDate,
A.stopDate = B.stopDate
from
#TableA A
inner join #TableC C on C.userName = A.userName
inner join #TableB B on B.userId = C.userId
select
*
from
#TableA
I solved it, here is my solution
UPDATE TableA
SET StartDate = up.StartDate, EndDate = up.EndDate
FROM TableB up WHERE up.UserID = (SELECT Id from TableC u where u.Name = TableA.UserName)

Temporary table in where clause

I need some records from Temporary table and for this I am trying to run following query:
DECLARE #temp_table TABLE (Id uniqueidentifier, Dates nvarchar(10))
INSERT #temp_table
SELECT ID,Right(Companies.UserDefined4, 10)
FROM Companies
Select *
From Companies,#temp_table
Where Companies.ID = #temp_table.Id
But in Where clause I am getting this error:
The scalar variable #temp_table must be declared.
The correct code should be like :
DECLARE #temp_table TABLE (Id uniqueidentifier, Dates nvarchar(10))
INSERT #temp_table
SELECT ID,Right(Companies.UserDefined4, 10)
FROM Companies
Select *
From Companies c
join #temp_table t
on c.ID = t.Id
Try
SELECT *
FROM Companies c
INNER JOIN #temp_table t ON c.ID = t.ID

Need help on writing a SQL Server query

There are two tables,
Table A
A_ID A_Field
1 blah1
2 blah2
3 blah3
........
============================================================
Table B (A_ID is foreign key references Table A's A_ID)
A_ID B_Field
1 a
1 b
1 c
2 a
2 b
2 c
What is the BEST way to get result like below:
A_ID A_Field B_Field
1 blah1 a,b,c
2 blah2 a,b,c
Thanks a lot for the replies, they all works, however, there is one more request, "For XML" dows NOT work on SQL SERVER 2000, unfortunately my domain service's DB is SQL Server 2000, is there a simple query work on SQL SERVER 2000?? Thanks!
Try something like (* Full Example* )
DECLARE #TableA TABLE(
A_ID INT,
A_Field VARCHAR(20)
)
INSERT INTO #TableA SELECT 1,'blah1'
INSERT INTO #TableA SELECT 2,'blah2'
INSERT INTO #TableA SELECT 3,'blah3'
DECLARE #TableB TABLE(
A_ID INT,
B_Field VARCHAR(20)
)
INSERT INTO #TableB SELECT 1,'a'
INSERT INTO #TableB SELECT 1,'b'
INSERT INTO #TableB SELECT 1,'c'
INSERT INTO #TableB SELECT 2,'a'
INSERT INTO #TableB SELECT 2,'b'
INSERT INTO #TableB SELECT 2,'c'
;WITH Vals AS (
SELECT a.A_ID,
a.A_Field,
b.B_Field
FROM #TableA a INNER JOIN
#TableB b ON a.A_ID = b.A_ID
)
SELECT p1.A_ID,
p1.A_Field
,STUFF(
(SELECT
', ' + p2.B_Field
FROM Vals p2
WHERE p2.A_ID=p1.A_ID
ORDER BY p2.A_ID
FOR XML PATH(''), TYPE
).value('.','varchar(max)')
,1,2, ''
) AS B_Field
FROM Vals p1
GROUP BY p1.A_ID,
p1.A_Field
Output
A_ID A_Field B_Field
1 blah1 a, b, c
2 blah2 a, b, c
"Best" is a relative term. I would probably use multiple queries and concatenate the string in code.
You can create a scalar UDF that takes A_ID as a parameter, and builds the denormalized string from table B. Your final SELECT would be:
SELECT A.A_ID, A.A_Field, dbo.myUDF(A.A_ID)
FROM A
To get the results as you are asking you need to join two tables. Here is an example:
SELECT A_ID, A_FIELD, B_FIELD
FROM Table A
LEFT JOIN Table B ON Table A.A_ID = Table B.A_ID
You would be using a group by function to concatenate the column B_Field values and you can refer to this post on help on cancatenating the strings
I don't know if it is the best way, but it works:
declare #rv table (a_id int, a_field varchar(50), b_field varchar(50))
insert into #rv (a_id, a_field) select a_id, a_field from a
declare #id int
declare #b varchar(50)
declare cur cursor for select a_id from #rv
open cur
fetch next from cur into #id
while ##fetch_status = 0 begin
set #b = ''
select #b = #b + ',' + b_field from b where a_id = #id
if len(#b) > 1 set #b = substring(#b, 2, len(#b)-1)
update #rv set b_field = #b where a_id = #id
fetch next from cur into #id
end
close cur
deallocate cur
select * from #rv
SELECT a.A_ID
, a.A_Field
, (SELECT CAST(b.B_Field+ ', ' AS VARCHAR(MAX))
FROM table_B b
WHERE (a.A_ID= b.A_ID)
FOR XML PATH ('')
)AS whatever FROM table_a a
This should work as you want. Cheers.
Try also this one
How to create a SQL Server function to "join" multiple rows from a subquery into a single delimited field?

SQL join different tables depending on row information

Suppose I have table A with a field that can be either 1 or 2...
How do I select such that for each row in table A, if the field is 1, join the select with table B and if the field is 2, join the select with table C?
(
SELECT MyField1, MyField2 FROM A
INNER JOIN B ON A.Id = B.Id
AND A.MyField = 1
)
UNION
(
SELECT MyField1, MyField2 FROM A
INNER JOIN C ON A.Id = C.Id
AND A.MyField = 2
)
Somethine like this can work
DECLARE #TableA TABLE(
ID INT
)
DECLARE #TableB TABLE(
ID INT,
Val VARCHAR(50)
)
DECLARE #TableC TABLE(
ID INT,
Val VARCHAR(50)
)
INSERT INTO #TableA SELECT 1
INSERT INTO #TableA SELECT 2
INSERT INTO #TableB SELECT 1, 'B'
INSERT INTO #TableC SELECT 2, 'C'
SELECT *
FROM #TableA a INNER JOIN
#TableB b ON a.ID = b.ID
AND a.ID = 1
UNION
SELECT *
FROM #TableA a INNER JOIN
#TableC c ON a.ID = c.ID
AND a.ID = 2