I have a view made like this
CREATE VIEW PEOPLE
AS
SELECT CustomerId, CustomerName FROM Customers
UNION ALL
SELECT EmployeeId, EmployeeName FROM Employees
UNION ALL
SELECT FriendId, FriendName From Friends
now I need to add unique ID for the view, because of course i can have a CustomerId = 15
and an EmployeeID = 15
So the trick I am doing is the following
SELECT
CAST('1' + CAST(CustomerId AS VARCHAR(30)) AS INT) as UniqueCustomerId,
CustomerId, CustomerName FROM Customers
UNION ALL
SELECT
CAST('2' + CAST(EmployeeId AS VARCHAR(30)) AS INT) as UniqueEmployeeId,
EmployeeId, EmployeeName FROM Employees
UNION ALL
SELECT
CAST('3' + CAST(FriendId AS VARCHAR(30)) AS INT) as UniqueFriendId,
FriendId, FriendName From Friends
Anyway this casting to varchar(30)
and back to int
is an overhead since I have many records.
Could you suggest a better approach?
If you've got to have a single id, just do math:
SELECT 1000000 + CustomerID AS UniqueCustomerId
, CustomerId
, CustomerName
FROM Customers
UNION ALL
SELECT 2000000 + EmployeeId AS UniqueEmployeeId
, EmployeeId
, EmployeeName
FROM Employees
UNION ALL
SELECT 3000000 + FriendId AS UniqueFriendId
, FriendId
, FriendName
FROM Friends
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With