Update more records with stored procedure - c#

I have the following records imported from excel to the database. The record count is 5,00,000.
EmpId Name City CityId
1 Ramesh LA ?
2 Kumar NewYork ?
I need to fetch the CityId from other table and insert into this CityId
The other table has the alias name for the cities and the cityId
CityId AliasName
1 LA
1 LosAngels
1 Los Angels
1 LA(USA)
I would like to call a stored procedure to update all 500000 records, as functions cannot be used for UPDATING record.
I need CityId field to be updated for each employee from Alias Table

you can do something like :
update employee
set cityid = b.cityid
from employee as a inner join city as b on a.city = b.aliasname

Hope this helps you out.
UPDATE UserDetails
SET UserDetails.CityID = City.ID
FROM City
WHERE City.AliasName = UserDetails.City

Would it not be easier to set the City as a foreign key rather than adding a redundant data column.
To answer your question, you can achieve this by running the following query. You can also make this into a stored procedure if it needs to be run occasionally.
UPDATE Employees SET CityId = (Select CityId FROM Cities where AliasName = City)

The following query will update the required data:
UPDATE Employees SET CityId = ISNULL((Select CityId FROM Cities where AliasName = City),0)

Related

How to loop through tables from SQL in c# without hardcoding

I'm creating a desktop application. I have 3 table (part time employees table, full time employees table and department table). The ID on department table is the foreign key.
I have created a connection string in my class. I'm trying to loop through the tables to get all departments that are assigned to employees, if a department is not assigned (delete it). I have the code in sql, but I want it in c#. Below is the sql code.
SELECT DepartmentName, DepartmentAddress
FROM Department
WHERE ID IN
(SELECT DISTINCT(ID)
FROM
PartTimeEmployees
);
If you simply want to DELETE departments that don't have a related employee, you can use an EXISTS:
DELETE D
FROM dbo.Department D
WHERE NOT EXISTS(SELECT 1
FROM dbo.Employee E
WHERE E.DepartmentID = D.ID);
There's no need to go any kind of "looping", as SQL is far better at doing these operations in a set-based way.
If deleting department not in part time employees table or full time employees table then you can get the department list as -
var departmentToDelete = departments.Where(d => !PartTimeEmployees.Any(emp => emp.DepartmentId == d.Id) && !FullTimeEmployees.Any(emp => emp.DepartmentId == d.Id)).ToList();

add column in table1 derived calculation from table2 's column

I have two tables
Employee
Finance
Employee contains 3 columns
id
Name
BaseSalary
Finance table contains 2 columns
id
BonusPercentage
I want to add TotalBonus column in Employee table. For calculation I am using BaseSalary from Employee table and BonusPercentage from Finance table.
TotalBonus = BaseSalary + (BaseSalary * BonusPercentage)
I can use this with stored procedure but i don't want. However, I created scalar function (calculateBonus) which returns TotalBonus but the problem is that i can't add column in table as i have dependency of BonusPercentage of Finance table.
In general i want employee table to have following:
id
Name
BaseSalary
TotalBonus
I know there are many ways but want in Employee table as I am using this table on C#.
Thanks
Assuming that there can be a maximum of one row in finance for each employee, you want a (left) join:
SELECT e.id,
e.name,
e.basesalary,
coalesce(f.bonuspercentage, 0) * e.basesalary totalbonus
FROM employee e
LEFT JOIN finance f
ON f.id = e.id;

fix data property name in gridview

I have 2 table :
table1: name, family, cityID
table2: cityID, cityName
I have a gridview that it's datasource is:
select * from table1, table2 where table1.cityID = table2.cityID
I disable autoCreatColumns
I add 3 columns to my datagrid.
in first column I fix the data property name to name
in second column I fix the data property name to family
but in third colum when I fix the data propery name to table2.cityName It dosent work...
I want to show the city name in third column.
Its an example but in fact, I have cityName in anouther table that I used, and if I use just cityName, makes error
can any body help me?
Thanks...
try to change
select * from table1, table2 where table1.cityID = table2.cityID
To
select table1.name as Name,table1.family as Family,table2.cityName as City from table1, table2 where table1.cityID = table2.cityID
SELECT name,family,cityName from table1 INNER JOIN table2 ON table1.cityID = table2.cityID
As you are doing inner joins with city ids on both tables..U will get matched Table IDs with name,citynames
You don't need to write table2.cityName, just write cityName and it should work.

Get the value of each field that updated in updating operation

i want get value of field after update,
for example i have two table
table1: ID Price UserID type
table2: IDLog ID(FK table1) OldPrice
and i update Price in table 1:
UPDATE table1
SET Price = '1111'
WHERE TYPE = 1
now i want befor every update get value ID table1 and insert into table2,
how i get value every field??
IMHO FOR UPDATE TRIGGER is the way to go. That way you can contain all logging logic inside your DB.
Better way to do it is using trigger on table1 (SQL Server side of course).
CREATE TRIGGER table1_update ON table1 FOR UPDATE
AS
BEGIN
INSERT INTO table2 (IDLog, OldPrice)
SELECT ID, Price
FROM deleted
INNER JOIN inserted ON
deleted.ID = inserted.ID
deleted.Price <> inserted.Price
END
You can use output clause:
update table1
output inserted.ID into table2
set Price='1111' where type=1
You can insert data to table2 before updating.
INSERT INTO table2
SELECT ID, Price from table1
WHERE TYPE = 1
--Update table1 after inserting
UPDATE table1
SET Price = '1111'
WHERE TYPE = 1
Other way to do is to create an update trigger for table1, which inserts the updated data to table2.

Get last inserted id

Is there any way I can get the last inserted ID if I am using SQL Server CE? I have 2 tables and when a new record is created, I want to be able to save the ID in the second table too.
SELECT ##IDENTITY
will retrieve the last auto-generated identity value in SQL Server.
I hope this example will help you.
INSERT INTO jobs (job_desc,min_level,max_level) VALUES ('A new job', 25, 100);
SELECT job_id FROM jobs WHERE job_id = ##IDENTITY;
use this query:
INSERT INTO Persons (FirstName) VALUES ('Joe');
SELECT ID AS LastID FROM Persons WHERE ID = ##Identity;
or you can view this link for more info:
http://blog.sqlauthority.com/2007/03/25/sql-server-identity-vs-scope_identity-vs-ident_current-retrieve-last-inserted-identity-of-record/
Assuming higher values of id are always newer, how about:
SELECT TOP 1 id FROM your_table ORDER BY id DESC
or:
SELECT MAX(id) FROM your_table
This worked fine for me
SELECT TOP (1) your_id FROM your_table ORDER BY your_id DESC

Categories