UPDATE DB4010.dbo.EntityStagedData
SET
EntityData = (
SELECT
geo.City + ' ' + geo.Description + ' ' + geo.Street + ' ' +
geo2.City + ' ' + geo2.Description + ' ' + geo2.Street
FROM DB4010.dbo.RouteTemplates templates
INNER JOIN DB4010.dbo.RouteTemplateClients clients
ON clients.RouteTemplateID = templates.RouteTemplateID
INNER JOIN DB4010.dbo.RouteTemplateStopMasters masters
ON masters.RouteTemplateClientID = clients.RouteTemplateClientID
INNER JOIN DB4010.dbo.RouteTemplateStopDetails details
ON details.RouteTemplateStopID = masters.PickupStopID
INNER JOIN DB4010.dbo.RouteTemplateStopDetails details2
ON details2.RouteTemplateStopID = masters.DeliveryStopID
INNER JOIN DB4010.dbo.Geofences geo
ON geo.GeofenceID = details.GeofenceID
INNER JOIN DB4010.dbo.Geofences geo2
ON geo2.GeofenceID = details2.GeofenceID
WHERE clients.RouteTemplateID = DB4010.dbo.EntityStagedData.EntityID
)
WHERE EXISTS ( SELECT RouteTemplateID FROM DB4010.dbo.RouteTemplates )
This is giving me an error:
Msg 515, Level 16, State 2, Line 1
Cannot insert the value NULL into
column 'EntityData', table 'DB4010.dbo.EntityStagedData'; column does
not allow nulls. UPDATE fails.
I can't, for the life of me, figure out how to update+Concatenate "EntityData" from the results of the inner Select statement...
I've made a few changes:
single-letter aliases for readability
fix to proprietary SQL Server UPDATE FROM syntax
elimination of uncorrelated WHERE EXISTS clause
You may still need to decide what to do in cases where geo.City etc. contain NULL values. You may need to simply wrap the expression in COALESCE or filter NULL rows out of the join altogether.
UPDATE s SET EntityData =
geo.City + ' ' + geo.Description + ' ' + geo.Street + ' ' +
geo2.City + ' ' + geo2.Description + ' ' + geo2.Street
FROM DB4010.dbo.EntityStagedData AS s
INNER JOIN DB4010.dbo.RouteTemplateClients AS c
ON c.RouteTemplateID = s.EntityID
INNER JOIN DB4010.dbo.RouteTemplates AS t
ON t.RouteTemplateID = c.RouteTemplateID
INNER JOIN DB4010.dbo.RouteTemplateStopMasters AS m
ON m.RouteTemplateClientID = c.RouteTemplateClientID
INNER JOIN DB4010.dbo.RouteTemplateStopDetails AS d
ON d.RouteTemplateStopID = m.PickupStopID
INNER JOIN DB4010.dbo.RouteTemplateStopDetails AS d2
ON d2.RouteTemplateStopID = m.DeliveryStopID
INNER JOIN DB4010.dbo.Geofences AS geo
ON geo.GeofenceID = d.GeofenceID
INNER JOIN DB4010.dbo.Geofences AS geo2
ON geo2.GeofenceID = d2.GeofenceID;
You can wrap the first section in a COALESCE statement as such:
SET EntityData = COALESCE(( SELECT geo.City + ' ' + geo.Description
+ ' ' + geo.Street + ' ' + geo2.City + ' ' + geo2.Description + ' '
+ geo2.Street
FROM DB4010.dbo.RouteTemplates templates
INNER JOIN DB4010.dbo.RouteTemplateClients clients ON clients.RouteTemplateID =
templates.RouteTemplateID
INNER JOIN DB4010.dbo.RouteTemplateStopMasters masters ON
masters.RouteTemplateClientID = clients.RouteTemplateClientID
INNER JOIN DB4010.dbo.RouteTemplateStopDetails details ON
details.RouteTemplateStopID = masters.PickupStopID
INNER JOIN DB4010.dbo.RouteTemplateStopDetails details2 ON
details2.RouteTemplateStopID = masters.DeliveryStopID
INNER JOIN DB4010.dbo.Geofences geo ON geo.GeofenceID = details.GeofenceID
INNER JOIN DB4010.dbo.Geofences geo2 ON geo2.GeofenceID = details2.GeofenceID
WHERE clients.RouteTemplateID = DB4010.dbo.EntityStagedData.EntityID ), '')
to set the value to a blank value.
If you want to get as much information as possible, wrap each individual portion in COALESCE statements to remove NULL values, such as:
SELECT COALESCE(geo.City, '') + ' ' + COALESCE(geo.Description, '') ...
That way, if one of your values in the sub-select is NULL, you won't get a NULL value as a result of the concatenation.
Related
I am create a stored procedure in SQL and I get the following error when I execute the query:
Conversion failed when converting the nvarchar value '11021,78542,12456,24521' to data type int.
Any idea why?
SELECT
A.Art_ID, A.Title
FROM
Art A
INNER JOIN
Iss I ON A.Iss_ID = I.Iss_ID
INNER JOIN
Sections S ON A.Section_ID = S.Section_ID
INNER JOIN
iPadSec IPS ON A.Sec_ID = IPS.Sec_ID
WHERE
A.Art_ID IN (SELECT CAST(Art_IDs AS int) /***error happens here***/
FROM Book_Art b
WHERE Sub_ID = 68)
AND I.Iss > dateadd(month, -13, getdate())
AND A.Active = 1
AND IPS.Active = 1
AND A.PDate <= getdate()
ORDER BY
PDate DESC, Art_ID DESC;
You cannot do what you want using in. First, it is a really bad idea to store ids in lists in strings. You should be using a junction table.
That said, sometimes this is necessary. You can rewrite this line of code as:
EXISTS (SELECT 1 /***error happens here***/
FROM Book_Art b
WHERE Sub_ID = 68 AND
',' + Art_IDs + ',' LIKE '%,' + cast(A.Art_ID as varchar(255)) + ',%'
)
However, the performance would generally be on the lousy side and there is little prospect of speeding this up without fixing the data structure. Use a junction table instead of a string to store lists.
Adding this line works for me.
declare #ids varchar(1000)
select #ids = art_ids from book_art where sub_id = #Sub_ID
EXECUTE ( 'SELECT A.Art_ID, A.Title'
+ ' FROM Art A'
+ ' INNER JOIN Iss I ON A.Iss_ID = I.Iss_ID'
+ ' INNER JOIN Sections S ON A.Section_ID = S.Section_ID'
+ ' INNER JOIN iPadSec IPS ON A.Sec_ID = IPS.Sec_ID'
+ ' WHERE A.Art_ID IN (' + #ids + ')'
+ ' AND I.Iss > dateadd(month, -13, getdate())'
+ ' AND A.Active = 1'
+ ' AND IPS.Active = 1'
+ ' AND A.PDate <= getdate()'
+ ' ORDER BY PDate DESC,'
+ ' Art_ID DESC;'
)
END
Thank you all for your help :)
I am trying to find something that does not match in 2 tables, this should be easy, now this works fine.
Select *
from Shop_Import SI
where SI.productID not in (SELECT productref FROM Shop_Import_Cats)
But this is the SQL I need to use, but it just does not return the 1 result that the above does:
SELECT
'Insert into Shop_Import_Cats values ('
+ CAST(p.ProductID AS VARCHAR) + ','
+ CAST(c.CategoryID AS VARCHAR) + ','
+ CAST(SI.ProductID AS VARCHAR) + ',getdate())
FROM
NB_Store_Products p
JOIN
NB_Store_ProductLang pl ON p.ProductID = pl.ProductID
JOIN
Shop_Import SI ON p.ProductRef = SI.ProductID
JOIN
NB_Store_CategoryLang CL ON SI.Primary_Category = CL.CategoryName
JOIN
NB_Store_Categories C ON CL.CategoryID = C.CategoryID
JOIN
Shop_Import_Cats SIC ON SI.ProductID = SIC.productref
WHERE
SI.ProductID NOT IN (SELECT SIC.productref
FROM Shop_Import_Cats SIC)
Based on advice here I tried this swapping the tables around and left joins to no avail - it returns null but should return one result.
Select 'Insert into Shop_Import_Cats values (' + CAST(p.ProductID as varchar) + ',' + CAST(c.CategoryID as varchar) + ',' + CAST(SI.ProductID as varchar) + ',getdate())'
from Shop_Import SI
left join NB_Store_Products P on SI.ProductID=p.ProductRef
left join NB_Store_ProductLang pl on p.ProductID=pl.ProductID
left join NB_Store_CategoryLang CL on SI.Primary_Category=CL.CategoryName
left join NB_Store_Categories C on CL.CategoryID=C.CategoryID
left join Shop_Import_Cats SIC on SI.ProductID=SIC.productref
where SI.ProductID not in (SELECT SIC.productref FROM Shop_Import_Cats SIC)
What am I doing wrong?
Try this instead:
SELECT
'Insert into Shop_Import_Cats values ('
+ CAST(coalesce(p.ProductID,' ') AS VARCHAR) + ','
+ CAST(coalesce(c.CategoryID,' ') AS VARCHAR) + ','
+ CAST(coalesce(SI.ProductID,' ') AS VARCHAR) + ',getdate())
from (
select
ProductID,
Primary_Category
/* insert any additional required columnx here */
from Shop_Import SI
where SI.ProductID not in (SELECT SIC.productref FROM Shop_Import_Cats SIC)
) SI
left join NB_Store_Products P on SI.ProductID = p.ProductRef
left join NB_Store_ProductLang pl on p.ProductID = pl.ProductID
left join NB_Store_CategoryLang CL on SI.Primary_Category = CL.CategoryName
left join NB_Store_Categories C on CL.CategoryID = C.CategoryID
left join Shop_Import_Cats SIC on SI.ProductID = SIC.productref
Now the WHERE condition will be executed on the same relvar as in the working example. I suspect that a null value is invoking 3-valued logic and propagating an UNKNOWN into a null record-set.
** edit Needed to add the SI to the 'from Shop_Import'
You just need to remove Shop_import_cats from the join:
Select 'Insert into Shop_Import_Cats values (' + CAST(p.ProductID as varchar) + ',' + CAST(c.CategoryID as varchar) + ',' + CAST(SI.ProductID as varchar) + ',getdate())'
from Shop_Import SI
left join NB_Store_Products P on SI.ProductID=p.ProductRef
left join NB_Store_ProductLang pl on p.ProductID=pl.ProductID
left join NB_Store_CategoryLang CL on SI.Primary_Category=CL.CategoryName
left join NB_Store_Categories C on CL.CategoryID=C.CategoryID
where SI.ProductID not in (SELECT SIC.productref FROM Shop_Import_Cats SIC)
I'm trying to create a query that will take multiple columns in a View and bring it into one column in the query. The values from each column needs to be separated by '|' (pipe).
I've tried:
1) (expression1 + '|' + expression2) AS xxxx, but if one expression has a null value, it makes the results 'null'.
2) CAST (expression1 as varchar (10)) + '|' + CAST (expression2 as varchar (10)) AS xxxx, but get the same results.
3) CASE (expression1 is null) then (' ') else (expression1) +'|' + CASE (expression2 is null) then (' ') else (expression2) END AS xxxx, but I get a syntax error near the keyword 'AS'.
Here's the full query using CASE.
SELECT DISTINCT dbo.REG.BUILDING, dbo.REG.CURRENT_STATUS, dbo.REG_CONTACT.LOGIN_ID, dbo.REG.LAST_NAME
, CASE WHEN dbo.View_MYAccess_Period1.CRSGRP1 is null then ' ' else dbo.View_MYAccess_Period1.CRSGRP1 + ' |' +
CASE WHEN dbo.View_MYAccess_Period2.CRSGRP2 is null then ' ' else dbo.View_MYAccess_Period2.CRSGRP2
END AS CRSGRP
FROM dbo.REG_CONTACT RIGHT OUTER JOIN
dbo.REG_STU_CONTACT ON dbo.REG_CONTACT.CONTACT_ID = dbo.REG_STU_CONTACT.CONTACT_ID RIGHT OUTER JOIN
dbo.REG ON dbo.REG_STU_CONTACT.STUDENT_ID = dbo.REG.STUDENT_ID LEFT OUTER JOIN
dbo.View_MYAccess_Period1 ON dbo.REG.STUDENT_ID = dbo.View_MYAccess_Period1.STUDENT_ID LEFT OUTER JOIN
dbo.View_MYAccess_Period2 ON dbo.REG.STUDENT_ID = dbo.View_MYAccess_Period2.STUDENT_ID
Any help for this newbie would be greatly appreciated!
Use ISNULL function,
SELECT DISTINCT dbo.REG.BUILDING, dbo.REG.CURRENT_STATUS, dbo.REG_CONTACT.LOGIN_ID, dbo.REG.LAST_NAME
, ISNULL(dbo.View_MYAccess_Period1.CRSGRP1,' ') + ' |' +
ISNULL(dbo.View_MYAccess_Period2.CRSGRP2,' ') CRSGRP
FROM dbo.REG_CONTACT RIGHT OUTER JOIN
dbo.REG_STU_CONTACT ON dbo.REG_CONTACT.CONTACT_ID = dbo.REG_STU_CONTACT.CONTACT_ID RIGHT OUTER JOIN
dbo.REG ON dbo.REG_STU_CONTACT.STUDENT_ID = dbo.REG.STUDENT_ID LEFT OUTER JOIN
dbo.View_MYAccess_Period1 ON dbo.REG.STUDENT_ID = dbo.View_MYAccess_Period1.STUDENT_ID LEFT OUTER JOIN
dbo.View_MYAccess_Period2 ON dbo.REG.STUDENT_ID = dbo.View_MYAccess_Period2.STUDENT_ID
In example 1, you might use the COALESCE(expression, fallback) function to force expression to return a fallback value if the expression is null. (Then tweak the rest of the logic accordingly.)
In your example 3, you need another END keyword:
CASE
(expression1 is null) then (' ')
ELSE (expression1) +'|' +
CASE (expression2 is null) then (' ') else (expression2) END
END AS xxxx
I've got code that if pulling info from two different tables, and I'm getting duplicates. I've tried DISTINCT in the SELECT statement, but I get lots of errors "ntext data type cannot be selected as DISTINCT because it is not comparable."
So my next attempt was to try GROUP BY, but I get errors "Column Person.Pers_FirstName is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
So my records have multiple relationship fields, but it's a problem because some records have none, one or more than one relationship (the options are NULL, project engineer, project owner, or project contractor). Current code only shows NULL and Project Engineer, but if there's records with the other two then they are excluded. If I include the other relationship descriptions then I get duplicates.
SELECT
RTRIM(ISNULL(Pers_FirstName, '')) + ' ' + RTRIM(ISNULL(Pers_LastName, '')) AS Pers_FullName,
RTRIM(ISNULL(oppocomp.Comp_PhoneCountryCode, '')) + ' ' + RTRIM(ISNULL(oppocomp.Comp_PhoneAreaCode, '')) + ' ' + RTRIM(ISNULL(oppocomp.Comp_PhoneNumber, '')) AS Comp_PhoneFullNumber,
RTRIM(ISNULL(oppocomp.Comp_FaxCountryCode, '')) + ' ' + RTRIM(ISNULL(oppocomp.Comp_FaxAreaCode, '')) + ' ' + RTRIM(ISNULL(oppocomp.Comp_FaxNumber, '')) AS Comp_FaxFullNumber,
RTRIM(ISNULL(Pers_PhoneCountryCode, '')) + ' ' + RTRIM(ISNULL(Pers_PhoneAreaCode, '')) + ' ' + RTRIM(ISNULL(Pers_PhoneNumber, '')) AS Pers_PhoneFullNumber,
RTRIM(ISNULL(Pers_FaxCountryCode, '')) + ' ' + RTRIM(ISNULL(Pers_FaxAreaCode, '')) + ' ' + RTRIM(ISNULL(Pers_FaxNumber, '')) AS Pers_FaxFullNumber,
Opportunity.*, oppocomp.Comp_Name, oppocomp.Comp_Territory, oppocomp.Comp_EmailAddress,
oppocomp.Comp_CompanyId, oppocomp.Comp_SecTerr, oppocomp.Comp_CreatedBy,
oppocomp.Comp_PrimaryUserID, Terr_Caption, Pers_Title, Pers_EmailAddress, Pers_SecTerr,
Pers_CreatedBy, Pers_PersonId, Pers_PrimaryUserID, Chan_Description,
oppocomp.Comp_ChannelID, (Oppo_Base_Currency.Curr_CurrencyID) AS Oppo_WeightedForecast_CID,
Pers_ChannelID ((Oppo_Forecast / Oppo_Forecast_Currency.Curr_Rate) * Oppo_Certainty / 100) AS Oppo_WeightedForecast,
Oppo_PrimaryAccountId AS Acc_AccountId, rend_Notes, renl_description,
relcomp.Comp_Name AS Rela_CompanyName
FROM Opportunity
LEFT JOIN Person ON Oppo_PrimaryPersonID = Pers_PersonID
LEFT JOIN Company AS oppocomp ON Oppo_PrimaryCompanyID = Comp_CompanyId
LEFT JOIN Territories ON Oppo_SecTerr = Terr_TerritoryId
LEFT JOIN Channel ON Chan_ChannelId = Oppo_ChannelId
LEFT JOIN RelatedEntityData ON Oppo_OpportunityId = rend_entity1id
LEFT JOIN RelatedEntityLinks ON rend_relatedentitylinkid = REnL_RelatedEntityLinkID
LEFT JOIN Company AS relcomp ON rend_entity2id = relcomp.Comp_CompanyId
LEFT JOIN Currency Oppo_Forecast_Currency ON Oppo_Forecast_CID = Oppo_Forecast_Currency.Curr_CurrencyID
LEFT JOIN Currency Oppo_Base_Currency
ON Oppo_Base_Currency.Curr_CurrencyID = (
SELECT CAST(CAST(Parm_Value AS NCHAR) AS INTEGER)
FROM Custom_SysParams
WHERE Parm_Name = 'BaseCurrency'
)
WHERE Oppo_Deleted IS NULL
AND (renl_description IS NULL OR renl_description = 'Project Engineer')
I am trying to use Delete statement in my Stored Procedure but it is giving me an error saying,
Invalid object name 'BRWSQLDC'.
and below is my Delete Statement:
set #Query = 'DELETE FROM ' + #DestLinkServer + ' FROM .HL2_61.dbo.ArtPDF AP JOIN .HL2_61.dbo.Article A on A.ArticleID = AP.ArticleID ' + ' WHERE ArticleKey = ' + CONVERT(VARCHAR, #Id)
When I execute it as below
DELETE FROM BRWSQLDC FROM .HL2_61.dbo.ArticlePDF AP JOIN .HL2_61.dbo.Article A on A.ArticleID = AP.ArticleID WHERE ArticleKey = -1591276581
Error is: Invalid object name 'BRWSQLDC'.
And if I try to execute the code as below:
'DELETE FROM ' + #DestLinkServer + ' .HL2_61.dbo.ArticlePDF AP JOIN .HL2_61.dbo.Article A on A.ArticleID = AP.ArticleID ' + ' WHERE ArticleKey = ' + CONVERT(VARCHAR, #Id)
when passing the values,
DELETE FROM BRWSQLDC .HL2_61.dbo.ArticlePDF AP JOIN .HL2_61.dbo.Article A on A.ArticleID = AP.ArticleID WHERE ArticleKey = -1591276581
error I am getting is:
Incorrect syntax near 'AP'.
Please help me how to join 2 tables in a delete and then delete that in the server if it exists.
You don't need a join but a proper WHERE clause.
Move you alias to after your delete, but you should also identify the table the ArticleKey comes from
DELETE AP
FROM BRWSQLDC.HL2_61.dbo.ArticlePDF AP
JOIN BRWSQLDC.HL2_61.dbo.Article A -- preface this with your server name for clarity
ON A.ArticleID = AP.ArticleID
WHERE A.ArticleKey = -1591276581
When you use join you have to tell from which table you want to delete rows:
DELETE dbo.Customer
FROM dbo.Customer cust INNER JOIN dbo.Person pers ON pers.ID_CUST = cust.ID_CUST