I am finding other solutions. I know my SQL Server query is not correct, but I need help to resolve the issue.
Below is my query and what I want to achieve with it for better understanding.
Gettring error like that
Msg 4104, Level 16, State 1, Line 37
The multi-part identifier “c.CountryCode” could not be bound.
Msg 4104, Level 16, State 1, Line 37
The multi-part identifier “c.Contact” could not be bound.
DECLARE @BusinessId NVARCHAR(100) = '99969011-7b1d-4c2d-92a6-fba9ca31a261',
@UserId UNIQUEIDENTIFIER = 'ece85174-fafd-43fb-a7a6-04c051f74de9';
DECLARE @RoleName NVARCHAR(50),
@BusinessPhoneNumber NVARCHAR(20);
-- Get the business phone number
SELECT TOP(1) @BusinessPhoneNumber = bm.PhoneNumberID
FROM BusinessDetails_Metas bm
INNER JOIN BusinessDetails b ON
bm.BusinessId = CAST(b.Id AS NVARCHAR(100))
WHERE bm.BusinessId = @BusinessId;
-- Get the role name of the user
SELECT TOP(1) @RoleName = r.[Name]
FROM Users u
INNER JOIN Role r ON r.Id = u.RoleId
WHERE u.Id = @UserId;
-- Main query to retrieve contact details and last conversation information
SELECT
c.ContactId,
c.[Name],
c.BusinessId,
c.UserId,
REPLACE(c.CountryCode, '+', '') + c.Contact AS Contact,
c.ChatStatus,
c.UserId AS Assignee,
c.Tags,
conv.TextMessage AS LastMessage,
conv.CreatedAt AS LastMessageAt,
c.IsSpam
FROM BusinessDetails_Metas bm
INNER JOIN BusinessDetails b ON bm.BusinessId = CAST(b.Id AS NVARCHAR(100))
INNER JOIN Users u ON u.CompanyId = bm.BusinessId
INNER JOIN Contacts c ON c.BusinessId = b.Id AND c.IsActive = 1
LEFT JOIN dbo.GetLastConversation(@BusinessPhoneNumber, REPLACE(c.CountryCode, '+', '') + c.Contact) conv ON
(conv.[From] = REPLACE(c.CountryCode, '+', '') + c.Contact OR conv.[To] = REPLACE(c.CountryCode, '+', '') + c.Contact)
WHERE b.Id = @BusinessId
AND (@RoleName IN ('Admin', 'Owner')
OR (@RoleName NOT IN ('Admin', 'Owner') AND c.UserId = @UserId));
ALTER FUNCTION [dbo].[GetLastConversation]
(
@WhatsappPhoneNumberId NVARCHAR(20),
@ToNumberId NVARCHAR(20)
)
RETURNS TABLE
AS
RETURN
(
SELECT TOP(1) *
FROM Conversations
WHERE ([From] = @WhatsappPhoneNumberId AND [To] = @ToNumberId)
OR ([From] = @ToNumberId AND [To] = @WhatsappPhoneNumberId)
ORDER BY CreatedAt DESC
);
GO
I created a new function to achieve the last conversation message and also tried using a subquery, but I was unable to resolve the issue. I am looking for a better solution.
What should I do?