I am trying to update fields in a table using a cursor but the update is not happening and I do not know why. Here is my SQL query:
DECLARE @EmployeeCompanyId int
SELECT DISTINCT EmployeeCompanyId
FROM [dbo].[tbl_Company_Employee_Contacts]
OPEN MY_CURSOR
FETCH NEXT FROM MY_CURSOR INTO @EmployeeCompanyId
WHILE @@FETCH_STATUS = 0
BEGIN
UPDATE [dbo].[tbl_Company_Employee_Contacts]
SET City = (SELECT TOP 1 Phone
FROM [dbo].[tbl_Company_Employee_Contacts]
WHERE EmployeeCompanyId = @EmployeeCompanyId
AND City IS NOT NULL)
WHERE EmployeeCompanyId = @EmployeeCompanyId
AND City IS NOT NULL
FETCH NEXT FROM MY_CURSOR INTO @EmployeeCompanyId
END
CLOSE MY_CURSOR
Table was created with a single piece of contact information per record. I am trying to consolidate all info into one record so that I can delete the others:
Something you could do is the following. you haven't provided any concrete sample data and desired results so this is just a mock-up but should give you something to work with, and no cursor
in sight.
/* sample data */
create table T (id int, EmployeeCompanyId int, Phone varchar(20), Street varchar(50))
insert into T values
(1, 10,'1234567890', null),
(1202, 10,'1234567890', null),
(78086, 10, null, 'Larose'),
(144887,10, null, 'Larose')
select * from T;
/* Update the highest ID row for each employee with data for each column*/
with u as (
select Max(Id) Id, Max(Phone) Phone, Max(Street) Street
from T
group by EmployeeCompanyId
)
update t set
t.phone=u.phone,
t.street=u.street
from u
join T on t.Id=u.Id
select * from T
/* delete all redundant rows for each employee */
/* This keeps the highest ID, if you want to put all data on the lowest ID, reverse the criteria accordingly */
with u as (
select EmployeeCompanyId, id, Row_Number() over (partition by EmployeeCompanyId order by id desc) rn
from t
)
delete from t
from u join t on t.Id=u.Id
where u.rn>1
select * from T
As other people have stated in the comments, I don't know why the CURSOR
is even necessary here. But the problem with your code above is that you didn't DECLARE
the CURSOR
first in your initial SELECT
.
DECLARE @EmployeeCompanyId int
DECLARE MY_CURSOR CURSOR FOR
SELECT DISTINCT EmployeeCompanyId
FROM [dbo].[tbl_Company_Employee_Contacts]
OPEN MY_CURSOR
FETCH NEXT FROM MY_CURSOR INTO @EmployeeCompanyId
WHILE @@FETCH_STATUS = 0
BEGIN
UPDATE [dbo].[tbl_Company_Employee_Contacts]
SET City = (SELECT TOP 1 Phone
FROM [dbo].[tbl_Company_Employee_Contacts]
WHERE EmployeeCompanyId = @EmployeeCompanyId
AND City IS NOT NULL)
WHERE EmployeeCompanyId = @EmployeeCompanyId
AND City IS NOT NULL
FETCH NEXT FROM MY_CURSOR INTO @EmployeeCompanyId
END
CLOSE MY_CURSOR
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.