I got a select statement. I want to add a join to this select statement and the join which I want to add is at the bottom of this code. why am I unable to add one more left outer join for this select statement? The join which I want to add is at the bottom. I also need to write a stored procedure for the entire select statement:
SELECT
FactId, UserType,
wr.WorkRequestId, wr.XerisUserKey,
xu.CsuserUserID UserId,
u.fname UserFName, u.lname UserLName,
b.PatientId, p.firstname PatFName, p.lastname PatLName,
GroupId, HospiceGroupKey GroupKey, WR.ContactKey,
C.ContactId, C.FirstName, C.LastName,
Convert(datetime, (Convert(varchar, SD.Date, 101) + ' ' + ST.TimeOfDay )) Start_dtm,
Convert(datetime, (Convert(varchar, CD.Date, 101) + ' ' + CT.TimeOfDay )) End_dtm,
DATEDIFF(s,Convert(datetime,(Convert(varchar, SD.Date, 101) + ' ' + ST.TimeOfDay)),
Convert(datetime, (Convert(varchar, CD.Date, 101) + ' ' + CT.TimeOfDay ))) WRDuration,
(Convert(Decimal(18, 3), DATEDIFF(s, Convert(datetime,(Convert(varchar, SD.Date, 101) + ' ' + ST.TimeOfDay )),
Convert(datetime, (Convert(varchar, CD.Date, 101) + ' ' + CT.TimeOfDay ))))) *
(Convert(Decimal(18,3),LineItemCount)/Convert(Decimal(18,3),PatientBucketItemCount)) Duration,
CallBackNumber, WorkRequestType,
B.LineItemCount, ArchiveLocation, Processed,
ArchiveQueueType, TQA, Exclude, CallId
FROM
bi.dbo.FactWorkRequestTouches (NOlock) WR
INNER JOIN
bi.dbo.BridgePatientWorkRequest B ON B.WorkRequestId = WR.WorkRequestId
INNER JOIN
bi.dbo.dimPatient (NOlock) P ON B.PatientId = P.CphPatientID
INNER JOIN
bi.dbo.DimXerisUsers (NOlock) XU ON WR.XerisUserKey = XU.XerisUserKey
INNER JOIN
cdc.dbo.csuser (NOlock) U ON XU.CsuserUserID = u.user_id
INNER JOIN
bi.dbo.DimTimeOfDay (NOlock) ST ON WR.StartTimeOfDayKey = ST.TimeKey
INNER JOIN
bi.dbo.DimTimeOfDay (NOlock) CT ON WR.CompletedTimeOfDayKey = CT.TimeKey
INNER JOIN
bi.dbo.DimDate (NOlock) SD ON WR.StartDateKey = SD.DateKey
INNER JOIN
bi.dbo.DimDate (NOlock) CD ON WR.CompletedDateKey = CD.DateKey
LEFT OUTER JOIN
bi.dbo.DimContact (Nolock) C ON WR.ContactKey = C.ContactKey
WHERE
CompletedDateKey = '20140131'
AND ArchiveQueueType = 0
AND PatientBucketItemCount <> 0
AND Exclude = 0
AND P.ENDDate is Null
This is the join I want to add to this select statement
left outer join
ssdba.excelleRx_WebFOCUS.dbo.DimHospiceHiearchy (nolock) h on b.groupid = h.group_id
You are not allowed to call a table valued function remotely (ie across servers).
There is a workaround here:
Workaround for calling table-valued function remotely in SQL Server has even more issues
And more info here:
http://social.msdn.microsoft.com/Forums/en-US/1f0d2885-faa2-496a-b010-edc441260138/remote-tablevalued-function-calls-are-not-allowed?forum=transactsql
Related
So, I have a rather simple query, which works, but very slow.
Is there a better way to optimize the query? Should I break out the LEFT JOINS on multiple columns? What about doing multiple runs and using Union ALL to join them together?
The tables have maybe 500,000 ROWS in them, and are indexed well.
Please help. Query takes forever to run
SELECT
ep.Id,
ep.DisplayName,
ep.EmailAddress,
COALESCE(
gs.DisplayNameMember + ' (' + gd.DisplayName + ')',
ea.DisplayName ,
ep.TrusteeUserAccountName,
ep.Trustee
) AS Trustee
FROM
dbo.ExchangePermissions ep WITH (NOLOCK)
LEFT JOIN dbo.GroupDetail gd WITH (NOLOCK) ON (ep.Trustee = gd.[Identity] OR ep.Trustee = gd.DisplayName OR ep.TrusteeUserAccountName = gd.SamAccountName)
LEFT JOIN dbo.GroupMemberShip gs WITH (NOLOCK) ON gd.name = gs.groupname
LEFT JOIN dbo.ExchangeAccount ea WITH (NOLOCK) ON (ep.Trustee = ea.[Identity] OR ep.Trustee = ea.DisplayName OR ep.TrusteeUserAccountName = ea.SamAccountName)
WHERE
ep.OTHERID= #MyParameter
The ORs in your LEFT JOINs are not helping performance at all. You should break them down into separate queries and UNION the results together. Working from Vykintas answer, we get the following:
SELECT
ep.Id,
ep.DisplayName,
ep.EmailAddress,
COALESCE(
gs.DisplayNameMember + ' (' + gd.DisplayName + ')',
ep.TrusteeUserAccountName,
ep.Trustee
) AS Trustee
FROM
dbo.ExchangePermissions ep WITH (NOLOCK)
LEFT JOIN dbo.GroupDetail gd WITH (NOLOCK) ON ep.Trustee = gd.[Identity]
LEFT JOIN dbo.GroupMemberShip gs WITH (NOLOCK) ON gd.name = gs.groupname
WHERE
ep.OTHERID= #MyParameter
UNION
SELECT
ep.Id,
ep.DisplayName,
ep.EmailAddress,
COALESCE(
gs.DisplayNameMember + ' (' + gd.DisplayName + ')',
ep.TrusteeUserAccountName,
ep.Trustee
) AS Trustee
FROM
dbo.ExchangePermissions ep WITH (NOLOCK)
LEFT JOIN dbo.GroupDetail gd WITH (NOLOCK) ON ep.Trustee = gd.DisplayName
LEFT JOIN dbo.GroupMemberShip gs WITH (NOLOCK) ON gd.name = gs.groupname
WHERE
ep.OTHERID= #MyParameter
UNION
SELECT
ep.Id,
ep.DisplayName,
ep.EmailAddress,
COALESCE(
gs.DisplayNameMember + ' (' + gd.DisplayName + ')',
ep.TrusteeUserAccountName,
ep.Trustee
) AS Trustee
FROM
dbo.ExchangePermissions ep WITH (NOLOCK)
LEFT JOIN dbo.GroupDetail gd WITH (NOLOCK) ON ep.TrusteeUserAccountName = gd.SamAccountName
LEFT JOIN dbo.GroupMemberShip gs WITH (NOLOCK) ON gd.name = gs.groupname
WHERE
ep.OTHERID= #MyParameter
I have a query that is getting some that is comparing a uniqueidentifier in the table and its a strange one.
SELECT * FROM vw_ryzex_CustomerAssets where BillToId='51ee47d2-eb97-4b12-8865-dab9a7f15a46'
So when i run this query i get the following error
Conversion failed when converting the nvarchar value '00000000-0000-0000-0000-000000000000' to data type int.
But when i select only the top 1000 i get the result and no error occurrs I tried Casting and converting checking nulls everything i could i tried following queries but did not work
SELECT * FROM vw_ryzex_CustomerAssets_V2 where CAST(BillToId as nvarchar(200))=Cast('51ee47d2-eb97-4b12-8865-dab9a7f15a46' as nvarchar(200))
SELECT * FROM vw_ryzex_CustomerAssets where (Case BillToId
when '00000000-0000-0000-0000-000000000000' Then NEWID()
ELSE BillToId
END) = '51ee47d2-eb97-4b12-8865-dab9a7f15a46'
Can anyone help me on this please..?
This is the view definition
ALTER VIEW [dbo].[vw_ryzex_CustomerAssets_V2] AS SELECT a.Id,
'~/Reports/BillToAssetDetails.aspx?btid='
+ CONVERT(VARCHAR(256), a.BillToId)
+ '&vidx=1&caid='
+ CONVERT(VARCHAR(256), a.Id) AS URL,
'~/Reports/BillToAssets.aspx?btid='
+ CONVERT(VARCHAR(256), a.BillToId)
+ '&vidx=1&caid='
+ CONVERT(VARCHAR(256), a.Id) AS EditUrl,
LEFT(a.PartDescription, 50) AS PartDescription,-- EKL:03042009
a.Quantity,
a.SerialNumber,
/* CASE ISNULL(s.Name,'') WHEN '' THEN a.Location ELSE s.Name + '(' + s.ErpId + ')
'+ a.Location END AS Location, */
a.Location,
s.NAME + '(' + s.ErpId + ')' AS SiteName,
--a.OrderId,
o.OrderGroupId AS OrderId,
a.OrderErpId,
a.OrderExt,
a.OrderLine,
a.DateCreated,
a.DateModified,
Isnull(ru.DisplayName, '') AS ModifiedBy,
a.BillToId,
a.PartNo,
b.NAME AS BillToName,
b.Description AS BillToDescription,
b.ErpId AS BillToErpId,
b.DateCreated AS BillToDateCreated,
b.DateModified AS BillToDateModified,
b.ModifiedBy AS BillToModifiedBy,
a.ProductId,
--p.ProductPartNo,
--p.ProductModel,
--p.ProductDescription as ProductDescription,
--p.ProductDateCreated,
--p.ProductDateModified,
--p.ProductModifiedBy,
Isnull(ol.UnitPrice, '0') AS UnitPrice,
ol.SalesTax,
Isnull(ol.TotalPrice, '0') AS TotalPrice,
ol.OrderErpId AS OrderLineId,
Isnull(ol.QuantityOrdered, '0') AS QuantityOrdered,
Isnull(ol.QuantityShipped, '0') AS QuantityShipped,
-- o.Created AS OrderDate,
Dateadd(mi, Datediff(mi, Getutcdate(), Getdate()), o.Created) AS OrderDate,
-- o.ShippedDate AS ShipDate,
Dateadd(mi, Datediff(mi, Getutcdate(), Getdate()), o.ShippedDate) AS ShipDate,
o.SalesPersonName AS SalesPersonDisplayName,
o.BillingCurrency AS Currency,
dbo.vw_PurchaseOrderPayments.PurchaseOrderPaymentNumber AS CustPo,
a.AssetNumber,
a.CustomerReference,
a.ModelNumber,
a.CustomField1Value AS xCust1,
a.CustomField2Value AS xCust2,
s.Id AS ShipToId,
s.AddressLine1 AS Address1,
s.AddressLine2 AS Address2,
s.AddressLine3 AS Address3,
s.City,
s.Country,
s.[State],
s.ZipCode AS Zip
FROM dbo.vw_PurchaseOrderPayments
RIGHT OUTER JOIN dbo.vw_PurchaseOrders AS o
ON dbo.vw_PurchaseOrderPayments.OrderFormId = o.OrderFormId -- EKL:03042009 chg from OrderGroupId to OrderFormId
RIGHT OUTER JOIN dbo.ryzex_CustomerAsset AS a
INNER JOIN dbo.ryzex_BillTo AS b WITH (NOLOCK)
ON a.BillToId = b.Id
AND Isnull(a.Inactive, 0) = 0
LEFT OUTER JOIN dbo.ryzex_ShipTo AS s WITH (NOLOCK)
ON a.ShipToId = s.Id
AND b.Id = s.BillToId
LEFT OUTER JOIN dbo.ryzex_Product AS p WITH (NOLOCK)
ON a.PartNo = p.ProductPartNo
LEFT OUTER JOIN dbo.vw_OrderLines AS ol
ON a.OrderErpId = ol.OrderErpId
AND a.OrderLine = ol.LineNumber
ON o.OrderErpNumber = a.OrderErpId
AND o.OrderExtensionNumber = a.OrderExt
LEFT OUTER JOIN dbo.ryzex_Users AS ru WITH (NOLOCK)
ON a.ModifiedBy = ru.Id
The BillToId that is coming from ryzex_CustomerAsset tbl is a not null uniqueidentifier
Working on a report that currently is in two columns on two datasets, an dam trying to combine the datasets into one single query. When I do the following query, I get The multi-part identifier "fa.InternalUserID" could not be bound.
--TST Group
SELECT A.AuditID,
A.FileID,
A.Description,
A.UserID,
IU.FirstName + ' ' + IU.LastName AS UserName,
FM.FileNumber,
SWITCHOFFSET(CONVERT(datetimeoffset, A.Date),'-05:00') AS 'LocalDateTime',
CONVERT(VARCHAR(10), A.Date, 101) AS 'Date',
CONVERT(VARCHAR(10), A.Date, 14) AS 'UnadjustedTime',
COUNT(FA.FileActionsID) AS ActionCount
FROM FileMain fm
INNER JOIN InternalUser AS IU ON fa.InternalUserID = IU.InternalUserID
JOIN FileActions FA on FA.FileID = FM.FileID
LEFT OUTER JOIN Audit AS A ON A.FileID = FM.FileID
WHERE (FM.OfficeID = 1)
AND (A.Description = 'File Opened'
OR A.Description = 'File Closed')
AND (A.Date >= GETDATE() - 2)
AND (IU.InternalUserID IN
(
--ID's go here
)
)
ORDER BY UserName, A.AuditID
Here are the original two queries I am combining:
--TST Group
SELECT A.AuditID,
A.FileID,
A.Description,
A.UserID,
IU.FirstName + ' ' + IU.LastName AS UserName,
FM.FileNumber,
SWITCHOFFSET(CONVERT(datetimeoffset, A.Date),'-05:00') AS 'LocalDateTime',
CONVERT(VARCHAR(10), A.Date, 101) AS 'Date',
CONVERT(VARCHAR(10), A.Date, 14) AS 'UnadjustedTime',
COUNT(FA.FileActionsID) AS ActionCount
FROM Audit AS A
INNER JOIN InternalUser AS IU ON A.UserID = IU.InternalUserID
LEFT OUTER JOIN FileMain AS FM ON A.FileID = FM.FileID
WHERE (FM.OfficeID = 1)
AND (A.Description = 'File Opened'
OR A.Description = 'File Closed')
AND (A.Date >= GETDATE() - 2)
AND (IU.InternalUserID IN
(
--ID's Go here
)
)
ORDER BY UserName, A.AuditID
and
SELECT IU.FirstName AS NAME,
COUNT(FA.FileActionsID) AS ActionCount
FROM FileActions AS FA
INNER JOIN InternalUser AS IU ON FA.ReceivedUserID = IU.InternalUserID
WHERE (FA.ReceivedDate > GETDATE() - 0)
AND (FA.ReceivedUserID IN (
--ID's go here
)
)
GROUP BY IU.FirstName
You have your joins in the wrong order. Currently you are trying to join InternalUser and FileActions when you've only mentioned FileMain and InternalUser (in that order) - you can't specify a condition against a table that hasn't been introduced to the join yet:
FROM FileMain fm
INNER JOIN InternalUser AS IU ON fa.InternalUserID = IU.InternalUserID
JOIN FileActions FA on FA.FileID = FM.FileID
LEFT OUTER JOIN Audit AS A ON A.FileID = FM.FileID
Should be (with obligatory schema prefixes added):
FROM dbo.FileMain fm
INNER JOIN dbo.FileActions FA on FA.FileID = FM.FileID
INNER JOIN dbo.InternalUser AS IU ON FA.InternalUserID = IU.InternalUserID
LEFT OUTER JOIN dbo.Audit AS A ON A.FileID = FM.FileID
I am getting the sql server error "the text ntext and image data types cannot be compared or sorted except when using is null or like" while executing
SELECT r.Shift, l.lab_title AS [Assigned Lab], u.user_name AS [L/A],
CONVERT(varchar(100), t.Time) + ' To ' + CONVERT(varchar(100), h.Time) AS Timing
FROM table_roaster_time_table AS r
INNER JOIN table_time AS t ON r.timeId = t.timeId AND r.timeId = t.timeId
INNER JOIN table_user AS u ON r.user_id = u.user_id
INNER JOIN table_labs AS l ON r.lab_id = l.lab_id
INNER JOIN table_time2 AS h ON r.timeId2 = h.timeId2
GROUP BY r.Shift, l.lab_title, u.user_name
Don't know what's the problem. I have used aggregate function also with it, just for formality but it's not working.
I'm guessing your r.Shift column is a text or ntext type. Because of this it cannot be used in a group by
One option might be to use a CAST on the suspect column, but you might loose data. Example:
SELECT r.Shift, l.lab_title AS [Assigned Lab], u.user_name AS [L/A], CONVERT(varchar(100), t.Time) + ' To ' + CONVERT(varchar(100), h.Time) AS Timing
FROM table_roaster_time_table AS r INNER JOIN
table_time AS t ON r.timeId = t.timeId AND r.timeId = t.timeId INNER JOIN
table_user AS u ON r.user_id = u.user_id INNER JOIN
table_labs AS l ON r.lab_id = l.lab_id INNER JOIN
table_time2 AS h ON r.timeId2 = h.timeId2
GROUP BY CAST(r.Shift as varchar(max), l.lab_title, u.user_name
You could also look at querying the data without the text column and then doing a second query to get the missing column. Example:
with temp as
(
SELECT l.lab_title AS [Assigned Lab], u.user_name AS [L/A], CONVERT(varchar(100), t.Time) + ' To ' + CONVERT(varchar(100), h.Time) AS Timing
FROM table_roaster_time_table AS r INNER JOIN
table_time AS t ON r.timeId = t.timeId AND r.timeId = t.timeId INNER JOIN
table_user AS u ON r.user_id = u.user_id INNER JOIN
table_labs AS l ON r.lab_id = l.lab_id INNER JOIN
table_time2 AS h ON r.timeId2 = h.timeId2
GROUP BY l.lab_title, u.user_name
)
SELECT r.Shift, t.lab_title AS [Assigned Lab], t.user_name AS [L/A] --etc
FROM table_roaster_time_table AS r
INNER JOIN temp as t
on r.id = t.id --or whatver
Also, this SQL seems unnecessary:
r.timeId = t.timeId AND r.timeId = t.timeId
I have the following query that retrieves what I need from the database:
SELECT
dbo.SafetySuggestionsLog.ID, dbo.SafetySuggestionsLog.Title,
dbo.SafetySuggestionsLog.Description, dbo.employee.Name,
dbo.SafetySuggestionsLog.Username, dbo.Divisions.DivisionShortcut,
dbo.SafetySuggestionsType.Type,
ISNULL(dbo.SafetySuggestionsStatus.Status, '-') AS Status,
dbo.SafetySuggestionsLog.DateSubmitted
FROM
dbo.employee
INNER JOIN
dbo.SafetySuggestionsLog ON dbo.employee.Username = dbo.SafetySuggestionsLog.Username
INNER JOIN
dbo.Divisions ON dbo.employee.DivisionCode = dbo.Divisions.SapCode
INNER JOIN
dbo.SafetySuggestionsType ON dbo.SafetySuggestionsLog.TypeID = dbo.SafetySuggestionsType.ID
LEFT OUTER JOIN
dbo.SafetySuggestionsStatus ON dbo.SafetySuggestionsLog.StatusID = dbo.SafetySuggestionsStatus.ID
ORDER BY
dbo.SafetySuggestionsLog.DateSubmitted DESC
Instead of showing the date under DateSubmitted column as (6/23/2012 7:15:00 AM), I want to display it as (Jun-2012).
How to do that?
You can have above format using below example query :
SELECT REPLACE(RIGHT(CONVERT(VARCHAR(11), CAST('6/23/2012 7:15:00 AM' AS DATETIME), 106), 8), ' ', '-') AS [Mon-YYYY]
In your query, you can try like this :
SELECT dbo.SafetySuggestionsLog.ID, dbo.SafetySuggestionsLog.Title, dbo.SafetySuggestionsLog.Description, dbo.employee.Name,
dbo.SafetySuggestionsLog.Username, dbo.Divisions.DivisionShortcut, dbo.SafetySuggestionsType.Type, ISNULL(dbo.SafetySuggestionsStatus.Status, '-') AS Status,
REPLACE(RIGHT(CONVERT(VARCHAR(11),dbo.SafetySuggestionsLog.DateSubmitted, 106), 8), ' ', '-') AS [Mon-YYYY]
FROM dbo.employee INNER JOIN
dbo.SafetySuggestionsLog ON dbo.employee.Username = dbo.SafetySuggestionsLog.Username INNER JOIN
dbo.Divisions ON dbo.employee.DivisionCode = dbo.Divisions.SapCode INNER JOIN
dbo.SafetySuggestionsType ON dbo.SafetySuggestionsLog.TypeID = dbo.SafetySuggestionsType.ID LEFT OUTER JOIN
dbo.SafetySuggestionsStatus ON dbo.SafetySuggestionsLog.StatusID = dbo.SafetySuggestionsStatus.ID
ORDER BY dbo.SafetySuggestionsLog.DateSubmitted DESC
Be sure,dbo.SafetySuggestionsLog.DateSubmitted column should be datetime type, otherwise cast it to datetime type
Another alternative that is more self-explanatory:
SELECT CONVERT(CHAR(3), DATENAME(MONTH, GETDATE())) + '-' + RTRIM(YEAR(GETDATE()));
Used in your query (along with aliases, which will make your queries much easier for you and others to read):
SELECT
sl.ID,
sl.Title,
sl.[Description],
e.employee.Name,
sl.Username,
d.DivisionShortcut,
st.[Type],
ISNULL(ss.[Status], '-') AS [Status],
sl.DateSubmitted,
MonthSubmitted = CONVERT(CHAR(3), DATENAME(MONTH, sl.DateSubmitted))
+ '-' + RTRIM(YEAR(sl.DateSubmitted))
FROM
dbo.employee AS e
INNER JOIN dbo.SafetySuggestionsLog AS sl
ON e.Username = sl.Username
INNER JOIN dbo.Divisions AS d
ON e.DivisionCode = d.SapCode
INNER JOIN dbo.SafetySuggestionsType AS st
ON sl.TypeID = st.ID
LEFT OUTER JOIN dbo.SafetySuggestionsStatus AS ss
ON sl.StatusID = ss.ID
ORDER BY
sl.DateSubmitted DESC;
In SQL Server 2012, this will be much easier with the new FORMAT() function, which has rough parity with the C# format function, supports optional culture, and doesn't require having to memorize style numbers:
SELECT FORMAT(GETDATE(), 'MMM-yyyy');