If I make a table variable here:
declare #Table Table (ProductID int, Color = varchar(60))
Then populate it of course, and try to use it in an Update with Join statement like below, I get errors.
UPDATE [Product]
SET [Product].[Active] = 1
,[Product].[Color] = t.[Color]
INNER JOIN #Table t
ON t.[ProductID] = [Product].[ProductID]
Error:
Msg 156, Level 15, State 1, Procedure
Incorrect syntax near the keyword 'INNER'.
Any suggestions how to do this?
You can also do this (works on SQL Server and all ANSI SQL conforming database):
UPDATE [Product] SET
[Product].[Active] = 1
,[Product].[Color] = t.[Color]
FROM #Table t
WHERE t.[ProductID] = [Product].[ProductID]
There's something to be desired from SQL Server's proprietary UPDATE FROM though, you can easily change the UPDATE statement to make it match whole table regardless if there's no matching rows.
It's easy to fashion this matched-rows-only update... http://www.sqlfiddle.com/#!3/8b5a3/26
update p SET
Qty = t.Qty
from Product p
inner join Latest t
on t.ProductId = p.ProductId;
...to an UPDATE that matches all rows, you merely change the INNER JOIN to LEFT JOIN: http://www.sqlfiddle.com/#!3/8b5a3/27
update p SET
Qty = ISNULL(t.Qty,0)
from Product p
left join Latest t
on t.ProductId = p.ProductId;
select * from Product;
Whereas if you want to fashion the ANSI SQL UPDATE with matched-rows-only ... http://www.sqlfiddle.com/#!3/8b5a3/28
update Product SET
Qty = t.Qty
from Latest t
where t.ProductId = Product.ProductId
...to UPDATE statement that matches all rows, you have to adjust your query a bit: http://www.sqlfiddle.com/#!3/8b5a3/29
update Product SET
Qty = ISNULL(t.Qty, 0)
from
(
select x.ProductId, lat.Qty
from Product x
left join Latest lat on lat.ProductId = x.ProductId
) as t
where t.ProductId = Product.ProductId;
Though as most choices in development, one should weigh the pros and cons in terms of code readability/maintainability against flexibility
Data sample:
create table Product
(
ProductId int primary key not null,
Name varchar(50) not null,
Qty int not null
);
insert into Product(Name,Qty) values
(1,'CAR',1),
(2,'Computer',1000),
(3,'Shoes',2);
create table Latest
(
ProductId int primary key not null,
Qty int not null
);
insert into Latest(ProductId, Qty) values
(2,2000),
(3,3);
Related
In the code there is a lot of rows will be inserted and the code gives me this error
[23000][2601] Cannot insert duplicate key row in object 'dbo.Estimates' with unique index 'IX_Estimates_EstimateNumber'. The duplicate key value is (10005)
Code:
INSERT INTO dbo.Estimates (EstimateNumber, Date, Comments, CustomerId)
SELECT
(SELECT MAX(Number) + 1 FROM EstimateNumber),
po.DateReceived,
po.Notes,
(SELECT Id FROM Customers WHERE Name = po.Customer)
FROM
staging.PricingTable po
LEFT JOIN
dbo.Estimates Es ON Es.Date = po.DateReceived
WHERE
Es.Date IS NULL;
The issue is happening because select MAX(Number)+1 FROM EstimateNumber in the select clause will not work as you expect and always return the same value for each row. Since there is an unique index, it will block the data insert. You can execute the select statement to verify this.
You can use a ROW_NUMBER() to fix this.
A sample sql code is follows :
declare #maxval integer ;
select #maxval = max(Number) from EstimateNumber ;
insert into dbo.Estimates ( EstimateNumber, Date,Comments, CustomerId )
select #maxval + ROW_NUMBER() OVER (ORDER BY c.Id), po.DateReceived, po.Notes, c.Id
from staging.PricingTable po
join Customers c on c.Name = po.Customer
left join dbo.Estimates Es on Es.Date = po.DateReceived
where Es.Date is null;
here I have used a local variable to hold max(Number) and incremenetd it using row_number. also moved the Cutomers from nested-select to a join
I have flat table which I have to join using EAN attribute with my main table and update gid (id of my main table).
id attrib value gid
1 weight 10 NULL
1 ean 123123123112 NULL
1 color blue NULL
2 weight 5 NULL
2 ean 331231313123 NULL
I was trying to pivot ean rows into column, next join on ean both tables, and for this moment everything works great.
--update SideTable
--set gid = ab_id
select gid, ab_id
from SideTable
pivot (max (value) for attrib in ([EAN],[MPN])) as b
join MainTable as c
on c.ab_ean = b.EAN
where b.EAN !='' AND c.ab_archive = '0'
When I am selecting both id columns is okey, but when I am uncomment first lines and delete select whole table is set with first gid from my main table.
It have to set my main id into all attributes where ID where ean is matched from my main table.
I am sorry for my terrible english but I hope someone can help me, with that.
The reason your update does not work is that you don't have any link between your source and target for the update, although you reference sidetable in the FROM clause, this is effectively destroyed by the PIVOT function, leaving no link back to the instance of SideTable that you are updating. Since there is no link, all rows are updated with the same value, this will be the last value encountered in the FROM.
This can be demonstrated by running the following:
DECLARE #S TABLE (ID INT, Attrib VARCHAR(50), Value VARCHAR(50), gid INT);
INSERT #S
VALUES
(1, 'weight', '10', NULL), (1, 'ean', '123123123112', NULL), (1, 'color', 'blue', NULL),
(2, 'weight', '5', NULL), (2, 'ean', '331231313123', NULL);
SELECT s.*
FROM #S AS s
PIVOT (MAX(Value) FOR attrib IN ([EAN],[MPN])) AS pvt;
You clearly have a table aliased s in the FROM clause, however because you have used pivot you cannot use SELECT s*, you get the following error:
The column prefix 's' does not match with a table name or alias name used in the query.
You haven't provided sample data for your main table, but I am about 95% certain your PIVOT is not needed, I think you can get your update using just normal JOINs:
UPDATE s
SET gid = ab_id
FROM SideTable AS s
INNER JOIN SideTable AS ean
ON ean.ID = s.ID
AND ean.attrib = 'ean'
INNER JOIN MainTable AS m
ON m.ab_EAN = ean.Value
WHERE m.ab_archive = '0'
AND m.ab_EAN != '';
As per comment to the question, you need to use update + select statement.
A standard version looks like:
UPDATE
T
SET
T.col1 = OT.col1,
T.col2 = OT.col2
FROM
Some_Table T
INNER JOIN
Other_Table OT
ON
T.id = OT.id
WHERE
T.col3 = 'cool'
As to your needs:
update a
set a.gid = p.ab_id
from SideTable As a
Inner join (
select gid, ab_id
from SideTable
pivot (max (value) for attrib in ([EAN],[MPN])) as b
join MainTable as c
on c.ab_ean = b.EAN
where b.EAN !='' AND c.ab_archive = '0') p ON a.ean = p.EAN
try and break it down a bit more like this..
update SideTable
set SideTable.gid = p.ab_id
FROM
(
select gid, ab_id
from SideTable
pivot (max (value) for attrib in ([EAN],[MPN])) as b
join MainTable as c
on c.ab_ean = b.EAN
where b.EAN !='' AND c.ab_archive = '0'
) p
WHERE p.EAN = SideTable.EAN
How can one update the same field's value using a different ID?
Customer ORderType
Matt 1
Jake 2
For all "Matt"s I want to set the orderType to 2 from Jake.
This doesnt work.
declare #X nvarchar (250)
set #x = (select OrderType from table where Customer = 'Matt')
update table
set OrderType = #x
where Customer = 'Jake'
You can include a FROM clause in an UPDATE query.
UPDATE C SET OrderType = J.OrderType
FROM [Table] C
CROSS JOIN [Table] J
WHERE C.Customer = 'Matt' AND J.Customer = 'Jake'
If you use a subquery instead, that subquery must return precisely one row.
Note also that your quoted line:
set #x = (select OrderType from table where Customer = 'Matt')
Can also be written as:
SELECT #x = OrderType FROM Table WHERE Customer = 'Matt'
People tend to overuse subqueries.
update table
set OrderType = (select top 1 OrderType from table where Customer = 'Matt')
where Customer = 'Jake'
update table
set OrderType = (select TOP 1 OrderType from table where Customer = 'Matt')
where Customer = 'Jake'
I have my database setup to allow a user to "Like" or "Dislike" a post. If it is liked, the column isliked = true, false otherwise (null if nothing.)
The problem is, I am trying to create a view that shows all Posts, and also shows a column with how many 'likes' and 'dislikes' each post has. Here is my SQL; I'm not sure where to go from here. It's been a while since I've worked with SQL and everything I've tried so far has not given me what I want.
Perhaps my DB isn't setup properly for this. Here is the SQL:
Select trippin.AccountData.username, trippin.PostData.posttext,
trippin.CategoryData.categoryname, Count(trippin.LikesDislikesData.liked)
as TimesLiked from trippin.PostData
inner join trippin.AccountData on trippin.PostData.accountid = trippin.AccountData.id
inner join trippin.CategoryData on trippin.CategoryData.id = trippin.PostData.categoryid
full outer join trippin.LikesDislikesData on trippin.LikesDislikesData.postid =
trippin.PostData.id
full outer join trippin.LikesDislikesData likes2 on trippin.LikesDislikesData.accountid =
trippin.AccountData.id
Group By (trippin.AccountData.username), (trippin.PostData.posttext), (trippin.categorydata.categoryname);
Here's my table setup (I've only included relevant columns):
LikesDislikesData
isliked(bit) || accountid(string) || postid(string
PostData
id(string) || posttext || accountid(string)
AccountData
id(string) || username(string)
CategoryData
categoryname(string)
Problem 1: FULL OUTER JOIN versus LEFT OUTER JOIN. Full outer joins are seldom what you want, it means you want all data specified on the "left" and all data specified on the "right", that are matched and unmatched. What you want is all the PostData on the "left" and any matching Likes data on the "right". If some right hand side rows don't match something on the left, then you don't care about it. Almost always work from left to right and join results that are relevant.
Problem 2: table alias. Where ever you alias a table name - such as Likes2 - then every instance of that table within the query needs to use that alias. Straight after you declare the alias Likes2, your join condition refers back to trippin.LikesDislikesData, which is the first instance of the table. Given the second one in joining on a different field I suspect that the postid and accountid are being matched on the same row, therefore it should be AND together, not a separate table instance. EDIT reading your schema closer, it seems this wouldn't be needed at all.
Problem 3: to solve you Counts problem separate them using CASE statements. Count will add the number of non NULL values returned for each CASE. If the likes.liked = 1, then return 1 otherwise return NULL. The NULL will be returned if the columns contains a 0 or a NULL.
SELECT trippin.PostData.Id, trippin.AccountData.username, trippin.PostData.posttext,
trippin.CategoryData.categoryname,
SUM(CASE WHEN likes.liked = 1 THEN 1 ELSE 0 END) as TimesLiked,
SUM(CASE WHEN likes.liked = 0 THEN 1 ELSE 0 END) as TimesDisLiked
FROM trippin.PostData
INNER JOIN trippin.AccountData ON trippin.PostData.accountid = trippin.AccountData.id
INNER JOIN trippin.CategoryData ON trippin.CategoryData.id = trippin.PostData.categoryid
LEFT OUTER JOIN trippin.LikesDislikesData likes ON likes.postid = trippin.PostData.id
-- remove AND likes.accountid = trippin.AccountData.id
GROUP BY trippin.PostData.Id, (trippin.AccountData.username), (trippin.PostData.posttext), (trippin.categorydata.categoryname);
Then "hide" the PostId column in the User Interface.
Instead of selecting Count(trippin.LikesDislikesData.liked) you could put in a select statement:
Select AccountData.username, PostData.posttext, CategoryData.categoryname,
(select Count(*)
from LikesDislikesData as likes2
where likes2.postid = postdata.id
and likes2.liked = 'like' ) as TimesLiked
from PostData
inner join AccountData on PostData.accountid = AccountData.id
inner join CategoryData on CategoryData.id = PostData.categoryid
USE AdventureWorksDW2008R2
GO
SET NOCOUNT ON
GO
/*
Default
*/
SET TRANSACTION ISOLATION LEVEL READ COMMITTED
GO
BEGIN TRAN
IF OBJECT_ID('tempdb.dbo.#LikesDislikesData') IS NOT NULL
BEGIN
DROP TABLE #LikesDislikesData
END
CREATE TABLE #LikesDislikesData(
isLiked bit
,accountid VARCHAR(50)
,postid VARCHAR(50)
);
IF OBJECT_ID('tempdb.dbo.#PostData') IS NOT NULL
BEGIN
DROP TABLE #PostData
END
CREATE TABLE #PostData(
postid INT IDENTITY(1,1) NOT NULL
,accountid VARCHAR(50)
,posttext VARCHAR(50)
);
IF OBJECT_ID('tempdb.dbo.#AccountData') IS NOT NULL
BEGIN
DROP TABLE #AccountData
END
CREATE TABLE #AccountData(
accountid INT
,username VARCHAR(50)
);
IF OBJECT_ID('tempdb.dbo.#CategoryData') IS NOT NULL
BEGIN
DROP TABLE #CategoryData
END
CREATE TABLE #CategoryData(
categoryname VARCHAR(50)
);
INSERT INTO #AccountData VALUES ('1', 'user1')
INSERT INTO #PostData VALUES('1','this is a post')
INSERT INTO #LikesDislikesData (isLiked ,accountid, postid)
SELECT '1', P.accountid, P.postid
FROM #PostData P
WHERE P.posttext = 'this is a post'
SELECT *
FROM #PostData
SELECT *
FROM #LikesDislikesData
SELECT *
FROM #AccountData
SELECT COUNT(L.isLiked) 'Likes'
,P.posttext
,A.username
FROM #PostData P
JOIN #LikesDislikesData L
ON P.accountid = L.accountid
AND L.IsLiked = 1
JOIN #AccountData A
ON P.accountid = A.accountid
GROUP BY P.posttext, A.username
SELECT X.likes, Y.dislikes
FROM (
(SELECT COUNT(isliked)as 'likes', accountid
FROM #LikesDislikesData
WHERE isLiked = 1
GROUP BY accountid
) X
JOIN
(SELECT COUNT(isliked)as 'dislikes', accountid
FROM #LikesDislikesData
WHERE isLiked = 0
GROUP BY accountid) Y
ON x.accountid = y.accountid)
IF (XACT_STATE() = 1 AND ERROR_STATE() = 0)
BEGIN
COMMIT TRAN
END
ELSE IF (##TRANCOUNT > 0)
BEGIN
ROLLBACK TRAN
END
How do you think about the solution? We create a new table SummaryReport(PostID,AccountID,NumberOfLikedTime,NumberOfDislikedTimes).
An user clicks on LIKE or DISLIKE button we update the table. After that, you can query as you desire. Another advantage, the table can be served reporting purpose.
CREATE TABLE #TempProducts (
Id uniqueidentifier,
ManufacturerId uniqueidentifier,
Number varchar(50),
PresentId uniqueidentifier null)
How to UPDATE PresentId field? I have different errors in this:
1) There is already an object named '#TempProducts' in the database.
UPDATE #TempProducts
SET #TempProducts.PresentId = p.Id
FROM #TempProducts JOIN Products p ON (#TempProducts.ManufacturerId = p.ManufacturerId AND #TempProducts.Number = p.Number)
WHERE #TempProducts.Id <> p.Id
2) The multi-part identifier "t.PresentId" could not be bound.
UPDATE #TempProducts
SET t.PresentId = p.Id
FROM #TempProducts t JOIN Products p ON (t.ManufacturerId = p.ManufacturerId AND t.Number = p.Number)
WHERE t.Id <> p.Id
For the Second Error please try:
UPDATE t
SET t.PresentId = p.Id
FROM #TempProducts t JOIN Products p ON (t.ManufacturerId = p.ManufacturerId AND t.Number = p.Number)
WHERE t.Id <> p.Id
UPDATE t
SET t.PresentId = p.Id
FROM #TempProducts t JOIN Products p ON (t.ManufacturerId = p.ManufacturerId AND t.Number = p.Number)
WHERE t.Id <> p.Id
This would be fix for a second error (UPDATE t instead of UPDATE #TempProducts). However, there is no way first query could produce mentioned error.
I am guessing you are executing your CREATE TABLE query again which is producing error because temp table already exists.
You should use a check like this when creating temp tables:
IF (OBJECT_ID('tempdb..#TempProducts') IS NOT NULL) DROP TABLE #TempProducts
CREATE TABLE #TempProducts (
Id uniqueidentifier,
ManufacturerId uniqueidentifier,
Number varchar(50),
PresentId uniqueidentifier null)
For problem 1:(Before the CREATE TABLE syntax )
if object_id(tempdb..#TempProducts) is not null
begin
drop table #TempProducts
end
And for problem 2 i think #techdo is correct.
UPDATE t
SET t.PresentId = p.Id
FROM #TempProducts t JOIN Products p
ON (t.ManufacturerId = p.ManufacturerId AND t.Number = p.Number)
WHERE t.Id <> p.Id
Can't comment due to rep restrictions, but the
IF (OBJECT_ID('tempdb..#TempProducts') IS NOT NULL) DROP TABLE #TempProducts" is no longer needed in SQL Server 2012 or higher. You can now use the simpler DROP TABLE IF EXISTS #TempProducts syntax.