Update of table1 with table2 values using SQL Server - c#

I want to update table1 with table2 mobile number, the common column in table1 and table2 is name, but table1 name is mixed with initial, table2 only has the name.
Can anyone tell how to update table1?
I've tried this:
update table1
set table1.mobile = table2.mobile
from table1
join table2 on table1.name = table2.name
Table1
Name Mobile
abc 123
def 456
Table2
Name Mobile
abc x null
def Y Null
I want to update table1 mobile in table2 mobile
I tried
update table1 set table1.mobile=table2.mobile from table1
join table2 on table1.name=table2.name

You can do this using sub-query.
update table1 set table1.mobile = (select TOP 1 table2.mobile from table2 where table2.name = substring(table1.name, 0, charindex(' ', table1.name)))
Edit:
I did a substring on the first word of the column value. The "anil y" will now be "anil".

You can try something like below:
Create table #table1
(
name varchar(10),
mobile int
)
insert into #table1 values ('Anil', 123)
insert into #table1 values ('abc', 888)
insert into #table1 values (NULL, 321)
Create table #table2
(
name varchar(10),
mobile int
)
insert into #table2 values ('Anil y', NULL)
insert into #table2 values ('z abc', NULL)
insert into #table2 values (NULL, NULL)
Update #table2
Set #table2.mobile = #table1.mobile
from #table2, #table1
Where charindex(#table1.name, #table2.name) > 0
Select * from #table2
Output:
Anil y 123
z abc 888
NULL NULL

Related

How to make a SQL query to display two columns values to one column?

I have a table structure like that as shown below. I want to show names under parent of names (where parent is ledger group)
DECLARE #t1 TABLE
(
ParentGroup varchar(20),
LedgerName varchar(20),
TotalDebit float,
credit float
)
INSERT INTO #t1
SELECT *
FROM Table1
INSERT INTO #t1
SELECT Distinct ParentGroup, ParentGroup, NULL, NULL
FROM Table1
Select LedgerName, TotalDebit, credit from #t1
group by LedgerName, TotalDebit, credit
ORDER BY (CASE WHEN TotalDebit IS NULL THEN 0 ELSE TotalDebit END)

Compare two dataset and add coulm in 1st dataset if exists in 2nd dataset

I have two datatable :
table1:
id value label
1 val1 lbl1
2 val2 lbl2
table2:
id value label
1 val1 lbl1
I want to compare two datatable and add a column to 1st table say 'assigned'= 'true' if it exists in table2 else false.
How do I do this? Either in c# or TSQL would help.
So the final result what I expect is:
id value label assigned
1 val1 lbl1 true
2 val2 lbl2 false
here since id=1 exists in both tables it is marked as assigned and id=2 which is only present in table1 and not in table2 then it is marked as false in assigned column.
EDIT
I have two separate select queries to get table1 and table2 data:
Here are my queries:
query1:
select Id,label,Values from
t1 inner join t2
on ID=t2.UDF1ValueID inner join t3
on t2.UDFID = t3.UDF_ID
where ID=15
query2
select Id,label,Values from t4 w
inner join t2 on(w.Id=t2.Id)
inner join t3 on (t3.ID=t2.ID)
inner join t4 on (t3.ID=t4.ID)
where w_Id=5 and t2.ID=15
You can do this using LEFT JOIN with a combination of CASE statement:
-- Sample Data
WITH table1(id, value, label) AS(
SELECT 1, 'val1', 'lbl1' UNION ALL
SELECT 2, 'val2', 'lbl2'
),
table2(id, value, label) AS(
SELECT 1, 'val1', 'lbl1'
)
-- Solution
SELECT
t1.*,
assigned = CASE WHEN t2.id IS NOT NULL THEN 1 ELSE 0 END
FROM table1 t1
LEFT JOIN table2 t2
ON t2.id = t1.id
declare #t table (Id int,val varchar(10),label varchar(10))
insert into #t (id,val,label)values(1,'val1','lbl1'),(2,'val2','lbl2')
declare #tt table (Id int,val varchar(10),label varchar(10))
insert into #tt (id,val,label)values(1,'val1','lbl1')
select tt.id,tt.val,tt.label,CASE WHEN ttt.Id IS NOT NULL THEN 'TRUE' ELSE 'FALSE' END 'Assigned'
from #t tt INNER JOIN #tt ttt ON tt.Id = ttt.Id
OR
select tt.id,tt.val,tt.label,CASE WHEN tt.Id IS NOT NULL THEN 'TRUE' ELSE 'FALSE' END 'Assigned'
from #t tt where exists (select 1 from #tt t where t.Id = tt.Id)
C# way of doing.
Please note this code here just handles schema but not data.
DataTable t1;
DataTable t2;
foreach( DataColumn c in t1.Columns)
{
if(!t2.Columns.Contains(c.ColumnName))
{
t2.Columns.Add(new DataColumn(c.ColumnName,c.DataType));
}
}
Working sample can be found here

Merging every two rows of data in a column in SQL Server

My table structure is..
Id UserId EventId
1 1 A
2 1 B
3 1 C
4 1 A
5 1 D
The output I need..
UserId EventStart EventEnd
1 A B
1 B C
1 C A
1 A D
I want every two rows to be merged into a row, so if the first row has A and 2nd has B then the first row of result table has A & B..
I have looked into PIVOT but unable to figure out how to get the results I want..
It would be great if I could solve this with sql else if it has to be solved in the middle layer, I'm using C#
Any help is sincerely appreciated..
Thanks..
Assuming that you have have an id column that specifies the ordering, you can get what you want using lead() (in SQL Server 2012+):
select userId, eventid as eventstart,
lead(eventid) over (partition by userid order by id) as eventend
from mytable t;
You are filtering out the last row, which you can do with a subquery (window functions aren't allowed in the where clause):
select t.*
from (select userId, eventid as eventstart,
lead(eventid) over (partition by userid order by id) as eventend
from mytable t
) t
where eventend is null;
In earlier versions of SQL Server, you can get the same effect in other ways, such as a correlated subquery or cross apply. Here is an example:
select t.*
from (select userId, eventid as eventstart,
(select top 1 t2.eventid
from mytable t2
where t2.userid = t.userid and
t2.id > t.id
order by t2.id
) as eventend
from mytable t
) t
where eventend is not null;
An easy approach would be using a CTE with a generated Row_Number() over the ID and joining over UserID and Rownumber.
declare #t Table([ID] [int] IDENTITY(1,1) NOT NULL, UserID int,EventID varchar(10))
insert into #t
Select 1,'A'
UNION ALL Select 1,'B'
UNION ALL Select 1,'C'
UNION ALL Select 1,'A'
UNION ALL Select 1,'D'
UNION ALL Select 2,'B'
UNION ALL Select 2,'C'
UNION ALL Select 2,'A'
UNION ALL Select 2,'D'
;With c as
(
Select UserID,EventID,Row_Number() OVER (Order by UserID,ID ) as RN
from #t
)
Select c1.UserID,c1.EventID as EventStart ,c2.EventID as EventEnd
from c c1
Join c c2 on c2.RN=c1.RN+1 and c2.UserID=c1.UserID

Select and update in same stored procedure and using result of select to update some value

Is there anything like
select Column_n from table1;
update table2 set column_m where column_a=Column_n ;
Which can be written in "same stored" procedure
You can UPDATE with JOIN directly like this:
UPDATE t2
SET t2.column_m = ...
FROM table2 AS t2
INNER JOIN table1 AS t1 ON t1.column_n = t2.column_a;
You can put it inside a stored procedure.
SQL Server has a lot of options for updating one table using data from other tables. Bellow you could find some of these solutions:
CREATE TABLE TableX
(
ID INT NOT NULL,
Col2 VARCHAR(10)
);
INSERT TableX (ID)
SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3;
CREATE TABLE TableY
(
ID INT NOT NULL,
Col2 VARCHAR(10)
);
INSERT TableY (ID,Col2)
SELECT 1,'A' UNION ALL SELECT 2,'B' UNION ALL SELECT 4,'D';
Solutions:
-- Solution #1
UPDATE TableX SET Col2 = NULL;
UPDATE x
SET Col2 = y.Col2
FROM TableX x INNER JOIN TableY y ON x.ID = y.ID;
SELECT * FROM TableX;
/*
ID Col2
----------- ----
1 A
2 B
3 NULL
*/
-- Solution #2
UPDATE TableX SET Col2 = NULL;
UPDATE TableX
SET Col2 =
(
SELECT y.Col2
FROM TableY y
WHERE TableX.ID = y.ID
)
SELECT * FROM TableX;
/*
ID Col2
----------- ----
1 A
2 B
3 NULL
*/
-- Solution #3
UPDATE TableX SET Col2 = NULL;
WITH UpdateTableX
AS
(
SELECT x.Col2 AS TargetCol2,
y.Col2 AS SourceCol2
FROM TableX x INNER JOIN TableY y ON x.ID = y.ID
)
UPDATE UpdateTableX
SET TargetCol2 = SourceCol2
SELECT * FROM TableX;
/*
ID Col2
----------- ----
1 A
2 B
3 NULL
*/
-- Solution #4 (SQL2008+)
UPDATE TableX SET Col2 = NULL;
MERGE INTO TableX x
USING TableY y ON x.ID = y.ID
WHEN MATCHED THEN
UPDATE SET Col2 = y.Col2;
SELECT * FROM TableX;
/*
ID Col2
----------- ----
1 A
2 B
3 NULL
*/
Now, if for target table one row can match many rows from source table
then you could have problems because some solutions can become UNSAFE (solutions #1 and #3)
Example: I insert another row in source table (TableY)
INSERT TableY (ID,Col2)
SELECT 1,'AA'
Now, for one row with ID=1 from source table there are 2 rows with ID=1 ({1,'A'} and {1,'AA'}). In this case, the solutions #1 or #3 will be executed successfully even these UPDATEs are unsafe:
UPDATE TableX SET Col2 = NULL;
UPDATE x
SET Col2 = y.Col2
FROM TableX x INNER JOIN TableY y ON x.ID = y.ID;
SELECT * FROM TableX;
/*
ID Col2
----------- ----------
1 A <-- In my test, SQL Server selected "first" row with ID=1 from source table (TableY) which has 2 rows with ID=1 ({1,'A'} and {1,'AA'})
2 B
3 NULL
*/
But if I change the order of rows in the source table TableY the results of he same UPDATE statements will be different:
TRUNCATE TABLE TableY;
INSERT TableY (ID,Col2)
SELECT 1,'AA' UNION ALL SELECT 2,'B' UNION ALL SELECT 4,'D';
INSERT TableY (ID,Col2)
SELECT 1,'A';
UPDATE TableX SET Col2 = NULL;
UPDATE x
SET Col2 = y.Col2
FROM TableX x INNER JOIN TableY y ON x.ID = y.ID;
SELECT * FROM TableX;
/*
ID Col2
----------- ----------
1 AA <-- The same UPDATE gives different results: 'AA' instead of 'A'
2 B
3 NULL
*/
If I execute solutions #2 and #4 then I will receive an exception (which is good)
Solution #2:
Msg 512, Level 16, State 1, Line 17
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
The statement has been terminated.
Solution #4:
Msg 8672, Level 16, State 1, Line 55
The MERGE statement attempted to UPDATE or DELETE the same row more than once. This happens when a target row matches more than one source row. A MERGE statement cannot UPDATE/DELETE the same row of the target table multiple times. Refine the ON clause to ensure a target row matches at most one source row, or use the GROUP BY clause to group the source rows.
because I know that I have to rewrite those statements
-- Solution #2
UPDATE TableX SET Col2 = NULL;
UPDATE TableX
SET Col2 =
(
SELECT MAX(y.Col2) -- or MIN or something else
FROM TableY y
WHERE TableX.ID = y.ID
)
-- Solution #4 (SQL2008+)
UPDATE TableX SET Col2 = NULL;
MERGE INTO TableX x
USING
(
SELECT a.ID, MAX(a.Col2) AS Col2 -- or MIN or something else
FROM TableY a
GROUP BY a.ID
) y ON x.ID = y.ID
WHEN MATCHED THEN
UPDATE SET Col2 = y.Col2;
You can do this
Declare #Var = varchar(50)
select #Var = Column_n from table1;
update table2 set column_m = newValue where column_a= #Var;

A Query Copy from 1 table into another + Values

I am trying to make this query work but i keep getting error.
insert into Table1 (CL1,CL2) Values ('TEST',CL2)
SELECT CL2 from Table2 where ID = 2
I am trying to take data from table 2 and put it in table 2 with the name TEST
Table1
is Empty
Table2
ID=2,SUP,SUP,SUP
if any one can help it would be great
insert into Table1 (CL1,CL2) SELECT 'TEST', CL2 from Table2 where ID = 2
Is this what you want:
INSERT INTO Table1 (CL1,CL2) VALUES ('TEST',(SELECT CL2 FROM Table2 WHERE ID=2))

Categories

Resources