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
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 have the following SQL statement so that I can script out view creation using if not exists with sp_executesql but the statement is giving me errors due to the single quotes around 1 in my last where statement. Is there any way around this?
IF NOT EXISTS (SELECT * FROM SYS.objects WHERE NAME = 'vw_JeopardyAlertDetails' AND TYPE = 'V')
EXEC sp_executesql #statement = N'CREATE VIEW [dbo].[vw_JeopardyAlertDetails]
AS
SELECT Main.TicketNumber, TS.TicketStateDesc, Main.ApptEnd, ISNULL(C.FirstName, '') AS FirstName, ISNULL(C.LastName, '') AS LastName, ISNULL(Main.CustomerID, '')
AS CustomerID, Main.ApptID, Main.ID, Main.TicketType
FROM (SELECT s.TicketState, s.TicketID AS ID, s.ApptEnd, dbo.Ticket.TicketNumber, dbo.Ticket.TimeOpened, dbo.Ticket.CreatedBy, dbo.Ticket.ReportedBy,
dbo.Ticket.ModifiedBy, dbo.Ticket.ChangedBy, dbo.Ticket.Priority, dbo.Ticket.ServingArea, dbo.Ticket.StructureLink, dbo.Ticket.CustomerID,
dbo.Ticket.TicketCategory, dbo.Ticket.TicketCode, s.ApptStart, s.TicketType, s.CanReschedule, ISNULL(s.ID, 0) AS ApptID
FROM dbo.Schedule AS s INNER JOIN
dbo.Ticket ON s.TicketID = dbo.Ticket.ID
WHERE (s.TicketState IN
(SELECT DISTINCT TicketState
FROM dbo.AlertJeopardyTicketState
WHERE (IsJeopardyState = '1'))) AND (s.ApptEnd >= CONVERT(DATETIME, CONVERT(VARCHAR(10), GETDATE(), 111) + ' ' + dbo.GetJeopardyStartTime()))
AND (s.ApptEnd <= GETDATE())) AS Main LEFT OUTER JOIN
dbo.Customer AS C ON Main.CustomerID = C.ID LEFT OUTER JOIN
dbo.TicketStatus AS TS ON Main.TicketState = TS.ID
GO' ;
ELSE PRINT N'vw_JeopardyAlertDetails ALREADY EXISTS'
GO
You'll need to double up those quotes in your Sql #statement, e.g.
ISNULL(C.FirstName, '')
needs to be
ISNULL(C.FirstName, '''')
Simplified fiddle here
I am trying to execute the following dynamic query but I got an error: Invalid column name 'cat'
DECLARE #SQLDelQuery AS NVARCHAR(1200)
DECLARE #MemberNames varchar(50)
SET #MemberNames = 'cat'
SET #SQLDelQuery = 'SELECT [Email] FROM [aspnet_Membership] am
INNER JOIN [aspnet_Users] u
ON (am.UserId = u.UserId)
INNER JOIN [Member] m
ON (am.UserId = m.UserId)
WHERE u.UserName IN (' + #MemberNames + ')
EXECUTE(#SQLDelQuery)
If I change it to the normal query I am fine:
SELECT [Email] FROM [aspnet_Membership] am
INNER JOIN [aspnet_Users] u
ON (am.UserId = u.UserId)
INNER JOIN [Member] m
ON (am.UserId = m.UserId)
WHERE u.UserName IN ('cat')
Anyone can point out my error? Thanks.
Since cat is a varchar you need to include single quotes around it and you need to place the closing parentheses for the IN clause inside of the sql string.
The new code will be:
DECLARE #SQLDelQuery AS NVARCHAR(1200)
DECLARE #MemberNames varchar(50)
SET #MemberNames = 'cat'
SET #SQLDelQuery = 'SELECT [Email] FROM [aspnet_Membership] am
INNER JOIN [aspnet_Users] u
ON (am.UserId = u.UserId)
INNER JOIN [Member] m
ON (am.UserId = m.UserId)
WHERE u.UserName IN (''' + #MemberNames + ''')'
EXECUTE(#SQLDelQuery)
See a SQL Fiddle Demo with the query string printed. This generates a query string like this:
SELECT [Email]
FROM [aspnet_Membership] am
INNER JOIN [aspnet_Users] u
ON (am.UserId = u.UserId)
INNER JOIN [Member] m
ON (am.UserId = m.UserId)
WHERE u.UserName IN ('cat') -- cat surrounded in single quotes
You need to pass it as a string to the dynamic query
SET #MemberNames = '''cat'''
Difference in the resulted query is
WHERE u.UserName IN (cat) -- cat is taking as a column name here
WHERE u.UserName IN ('cat') -- cat is taking as a string here
Your string:
WHERE u.UserName IN (' + #MemberNames + ')
will evaluate to:
WHERE u.UserName IN (cat)
because the apostrophes you have are just encapsulating the string, and there are no extra apostrophes around the string literal.
You need:
WHERE u.UserName IN (''' + #MemberNames + ''')
Alternately, you can leave your query as is, and seperate each ID with apostrophes in your #MemberNames variable:
SET #MemberName = '''cat''' -- for a single user
SET #MemberName = '''cat'', ''dog''' -- for multiple users
Your dynamic query uses ' characters as the string delimiter, so the last line ends up reading like this after the string is built:
WHERE u.UserName IN (cat)
According to this, cat reads like a column name.
To fix it, you need to include escaped ' characters in either the definition of
`SET #MemberNames = '''cat'''`
or in the string being used to build the sql:
`WHERE u.UserName IN (''' + #MemberNames + ''')'`
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.