Query
create table Emp(empId int primary key, EmpName varchar(50),MngrID int)
insert into Emp(empId,EmpName,MngrID)values(1,'A',2)
insert into Emp(empId,EmpName,MngrID)values(2,'B',null)
create table Mngr(MngrId int primary key, MngrName varchar(50))
insert into Mngr(MngrId,MngrName)values(1,'m1')
insert into Mngr(MngrId,MngrName)values(2,'m2')
I want to fetch the record in Emp table for MngrId Column that show the name of Manger instead of MngrId.
sql fiddle My fiddle
You need to use a join.
select e.empId, e.EmpName, m.MngrName
from Emp e
inner join Mngr m on m.MngrId = e.MngrID
Related
This question already has answers here:
Retrieving last record in each group from database - SQL Server 2005/2008
(2 answers)
Closed 2 years ago.
Can you tell how to find the last updated post of the employee from the table. Two tables :Employee and EmployeeDetails. Employee fields are: EmployeeID ,EmployeeName EmployeeDetails fields are: EmployeeID, Designation, PromotionDate.
How to find the current Designation of an employee if we give an EmployeeID. Using function. I want to create a simple function to get the Designation according to the current Designation (Latest PromotionDate ) using the EmployeeID, then join with Employee table.
DROP TABLE IF EXISTS Employee
CREATE TABLE Employee
(
EmployeeID INT NOT NULL PRIMARY KEY IDENTITY(1000,1),
EmployeeName VARCHAR(25)
)
INSERT INTO Employee VALUES('AAA');
INSERT INTO Employee VALUES('LAAA');
INSERT INTO Employee VALUES('RSSS');
INSERT INTO Employee VALUES('SEEE');
INSERT INTO Employee VALUES('CFFF');
INSERT INTO Employee VALUES('SEEEW');
INSERT INTO Employee VALUES('MCCC');
INSERT INTO Employee VALUES('DERR');
INSERT INTO Employee VALUES('DERR');
INSERT INTO Employee VALUES('DERW');
SELECT * FROM Employee
DROP TABLE EmployeeDetails
CREATE TABLE EmployeeDetails
(
EmployeeID INT FOREIGN KEY REFERENCES Employee(EmployeeID),
Designation VARCHAR(25),
PromotionDate Date
)
INSERT INTO EmployeeDetails VALUES(1000,'www','2020-11-20');
INSERT INTO EmployeeDetails VALUES(1000,'qqq','2020-01-23');
INSERT INTO EmployeeDetails VALUES(1009,'qqq','2020-09-20');
SELECT * FROM EmployeeDetails
SELECT
E.EmployeeID,
E.EmployeeName,
ED.Designation, ED.PromotionDate
FROM
Employee E
JOIN
EmployeeDetails ED ON E.EmployeeID = ED.EmployeeID
I wrote a function for this, but I don't know how to incorporate it with the query:
CREATE FUNCTION GetOnlyTheCurrentPost
( #EmpID INT)
RETURNS DATE
AS
BEGIN
DECLARE #PromoDate DATE
SELECT #PromoDate= MAX(PromotionDate)
FROM EmployeeDetails
WHERE EmployeeID = #EmpID
RETURN(#PromoDate)
END
I changed the function like this as below
ALTER FUNCTION [dbo].[GetOnlyTheCurrentPost]
( #PromoDate DATE)
RETURNS DATE
AS
BEGIN
SELECT #PromoDate= MAX(PromotionDate)
FROM EmployeeDetails
RETURN(#PromoDate)
END
SELECT
E.EmployeeID,
ED.Designation,[dbo].[GetOnlyTheCurrentPost](ED.PromotionDate) AS LatestPost
FROM
Employee E
JOIN
EmployeeDetails ED
ON E.EmployeeID = ED.EmployeeID
This will show all the records not only the latest post but also every records.
Again, I changed my function. I want to get the current Designation, if i give the EmployeeID Like, SELECT [dbo].[GetOnlyTheCurrentDesignation](1011). Output should be printed according to the given corresponding EmployeeID Output : ProjectManager
ALTER FUNCTION GetOnlyTheCurrentDesignation
(#EmpID INT)
RETURNS VARCHAR(MAX)
AS
BEGIN
DECLARE #Designation VARCHAR(25)
SELECT #Designation=Designation, MAX(PromotionDate)
FROM EmployeeDetails
WHERE EmployeeID = #EmpID
RETURN(#Designation)
END
Please tell me a solution to fix this
Try something like this:
SELECT
E.EmployeeID,
E.EmployeeName,
ED.Designation, ED.PromotionDate
FROM
Employee E
JOIN
(SELECT * FROM EmployeeDetails ED2
WHERE PromotionDate = (SELECT MAX(PromotionDate)
FROM EmployeeDetails
WHERE EmployeeID = ED2.EmployeeID)) ED
ON E.EmployeeID = ED.EmployeeID
I want to generate unique employee code at a time of inserting a single record in INSERT stored procedure.
First-time procedure call will generate employee code as E0001, the second call will generate E0002, ...
The expected output should look like,
EmployeeCode EmployeeName
-------------------------------
E0001 A
E0002 B
E0003 C
E0004 D
E0005 E
' '
' '
' '
E9999 ZZZ
You can embed a sequence value into a custom-formatted string in a default, and enforce it with a check constraint. Like this:
--drop table if exists Employee
--drop sequence seq_Employee
--go
create sequence seq_Employee
start with 1
increment by 1
go
CREATE TABLE Employee
(
EmployeeCode char(5) PRIMARY KEY
default 'E' + format((next value for seq_Employee),'0000' )
check (EmployeeCode like 'E[0-9][0-9][0-9][0-9]'),
EmployeeName VARCHAR(50) NOT NULL
)
go
insert into Employee(EmployeeName)
values ('A'),('B'),('C'),('D'),('E')
select *
from Employee
Outputs
EmployeeCode EmployeeName
------------ --------------------------------------------------
E0001 A
E0002 B
E0003 C
E0004 D
E0005 E
Use an identity column to create a unique id. Then use this column for references from other tables. You can create a code if you like as a computed column:
create table employees (
employeeId int identity(1, 1) primary key,
employeeName varchar(255),
employeeCode as (concat('E', format(employeeId, '00000')))
);
Here is a db<>fiddle.
Use a database sequence number in your procedure to provide you the values. In order to get the value 'E' appended, concatenate 'E' with the sequence number in the query.
Use this link to understand the concept of database sequence number in sql server
CREATE SEQUENCE dbo.Seq
START WITH 1
INCREMENT BY 1;
GO
DECLARE #T TABLE (
E_CODE VARCHAR(50) PRIMARY KEY,
E_Name VARCHAR(MAX)
);
INSERT INTO #T VALUES (CONCAT('E',FORMAT(NEXT VALUE FOR dbo.SEQ,'0000')),'A')
INSERT INTO #T VALUES (CONCAT('E',FORMAT(NEXT VALUE FOR dbo.SEQ,'0000')),'B')
INSERT INTO #T VALUES (CONCAT('E',FORMAT(NEXT VALUE FOR dbo.SEQ,'0000')),'C')
SELECT * FROM #T
I have two database,where two table are same with all schema.
I want to move specific records of employees and employeesrates with all columns of both tables.
below is the query.
CREATE TABLE #emp
(
empID INT IDENTITY(1, 1) primary key ,
Firstname varchar(20)
);
CREATE TABLE #empRates
(
ID INT IDENTITY(1, 1) primary key ,
empid int, -- foreign key from #emp
rate decimal(10,3),
startdate datetime,
enddate datetime,
);
insert into #emp (firstname) values('First')
insert into #emp (firstname) values('Second')
insert into #emp (firstname) values('Third')
insert into #empRates(empid,rate,startdate,enddate) values(1,10,'2020/01/10','2020/01/20')
insert into #empRates(empid,rate,startdate,enddate) values(1,15,'2020/01/20','2020/01/30')
insert into #empRates(empid,rate,startdate,enddate) values(2,10,'2020/01/10','2020/01/20')
insert into #empRates(empid,rate,startdate,enddate) values(3,15,'2020/01/20','2020/01/30')
select * from #emp
select * from #empRates
drop table #emp
drop table #empRates
Here both database on same server. Database1 and Database2.
below my query which tried.
insert into database2..empRates(empid,rate,startdate,enddate) select empid,rate,startdate,enddate
from database1..empRates
Here my problem is both database have different records,so identity are different,so after insert other employee rates get displayed for another like mashed up.
I am using sql server 2012.
can you please provide the way.
You should take a look at this post --> How to turn IDENTITY_INSERT on and off using SQL Server 2008?
This way you can specify value for id column during insert, so rows on destination databases will keep IDs from origin.
Hope it helps!
I'm having a table like this
Create table test1(emp_id decimal(5,0), emp_name varchar(20));
Insert into test1(2015,'XYZ');
Insert into test1(2016,'XYZ2');
Now I want to update emp_id to row_number()
or
add new column into same table like (emp_no integer) to row_number().
can anyone please tell me the query for this?
You need to use UPDATE FROM:
UPDATE test1
FROM
( SELECT ROW_NUMBER() OVER (ORDER BY emp_id) AS rn,
emp_id
FROM test1
) AS src
SET emp_id = src.rn
WHERE test1.emp_id = src.emp_id -- must be unique column(s)
Btw, instead of updating all rows of a table it might be better to INSERT/SELECT or MERGE the SELECT into a new table. You must do it if there's no unique column, you should if emp_id is the PI of your table (otherwise performance will be horrible).
Create table test1(
emp_id decimal(5,0),
emp_name varchar(20),
emp_no INTEGER GENERATED ALWAYS AS IDENTITY
(START WITH 1
INCREMENT BY 1
)
);
Insert into test1(2015,'XYZ1',2);
Insert into test1(2016,'XYZ2',2);
Insert into test1(2015,'XYZ3',null);
Insert into test1(2016,'XYZ4',null);
I have a emp table,
CREATE TABLE [dbo].[Emp](
[EmpId] [int] NULL,
[EmpName] [nvarchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[ManagerId] [int] NULL
) ON [PRIMARY]
Now, insert below values into the table
Insert Into Emp Values(1,'A',0)
Insert Into Emp Values(2,'B',1)
Insert Into Emp Values(3,'C',2)
Insert Into Emp Values(4,'D',2)
Insert Into Emp Values(5,'E',4)
Insert Into Emp Values(6,'F',4)
Insert Into Emp Values(7,'G',4)
Insert Into Emp Values(8,'H',6)
Insert Into Emp Values(9,'I',5)
Insert Into Emp Values(10,'J',7)
Insert Into Emp Values(11,'K',4)
I want to list employee name and their manager name in select statement.
What I am doing now is creating a temporary table which has all manager name and their Id.
Then getting the name from the manager table based on Id.
But I know this is not a correct way, in fact it is complex.
You should use a recursive CTE (Common Table Expression) for this:
-- define the recursive CTE and give it a name
;WITH Hierarchy AS
(
-- "anchor" - top-level rows to select, here those with ManagerId = 0
SELECT EmpId, EmpName, NULL AS 'MgrId', CAST(NULL AS NVARCHAR(50)) AS 'MgrName', 1 AS 'Level'
FROM dbo.Emp
WHERE ManagerId = 0
UNION ALL
-- recursive part - join an employee to its manager via ManagerId -> mgr.EmpId
SELECT e.EmpId, e.EmpName, mgr.EmpId, mgr.EmpName, mgr.Level + 1 AS 'Level'
FROM dbo.Emp e
INNER JOIN Hierarchy mgr ON e.ManagerId = mgr.EmpId
)
SELECT * FROM Hierarchy
You are correct: you don't have to use a temporary table just for this. Try using recursive queries. Take a look at this link on MSDN. There is an example with ManagerId/EmployeeID. Just as in your query.