TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
Atul Patil
NA
586
72.9k
How optimize query?
Jan 18 2019 3:40 AM
DECLARE
@page INT=-1, @size INT=-1, @search_query VARCHAR (50)=NULL, @genericSearch INT=1
--AS
IF (@page = -1)
BEGIN
SET @page = 1;
SET @size = (SELECT IIF (COUNT(1) > 0, COUNT(1), 1)
FROM user_device_location
WHERE is_active = 1);
END
BEGIN
WITH activeUserDetails
AS (SELECT udl.id,
udl.user_id,
u.FirstName,
u.LastName,
u.FirstName + ' ' + u.LastName AS user_full_name,
udl.mac_address,
udl.latitude,
udl.longitude,
udl.level,
udl.device_type,
udl.device_token,
udl.user_access_token,
udl.battery_level,
udl.is_active,
udl.added_by,
udl.added_on,
udl.modified_by,
udl.modified_on,
ROW_NUMBER() OVER (PARTITION BY udl.mac_address ORDER BY udl.added_on DESC) AS recencey
FROM user_device_location AS udl
INNER JOIN
users AS u
ON u.UserId = udl.user_id
)
SELECT aud.id,
aud.user_id,
aud.FirstName,
aud.LastName,
aud.user_full_name,
aud.mac_address,
aud.latitude,
aud.longitude,
aud.level,
aud.device_type,
aud.device_token,
aud.user_access_token,
aud.battery_level,
aud.is_active,
aud.added_by,
aud.added_on,
aud.modified_by,
aud.modified_on,
Count(*) OVER () AS total_rows
FROM activeUserDetails AS aud
WHERE aud.recencey = 1
AND aud.is_active = 1
AND ((@genericSearch = 1
AND (aud.FirstName LIKE '%' + isnull(@search_query, aud.FirstName) + '%'
OR aud.LastName LIKE '%' + isnull(@search_query, aud.LastName) + '%'
OR aud.device_type LIKE '%' + isnull(@search_query, aud.device_type) + '%'
OR aud.mac_address LIKE '%' + isnull(@search_query, aud.mac_address) + '%'
OR aud.user_full_name LIKE '%' + @search_query + '%'))
OR (@genericSearch <> 1
AND aud.FirstName LIKE '%' + isnull(@search_query, aud.FirstName) + '%'
OR aud.LastName LIKE '%' + isnull(@search_query, aud.LastName) + '%'
OR aud.device_type LIKE '%' + isnull(@search_query, aud.device_type) + '%'
OR aud.mac_address LIKE '%' + isnull(@search_query, aud.mac_address) + '%'
OR aud.user_full_name LIKE '%' + @search_query + '%'))
ORDER BY aud.id DESC
OFFSET ((@page - 1) * @size) ROWS FETCH NEXT @size ROWS ONLY;
END
Reply
Answers (
2
)
Passing Table Type Variables to User Defined Functions
display two table