Trying to add a column (Total_Parts) with
ALTER TABLE ADD
statement but when I execute the query, it says the column I'm adding is an invalid column name and my column doesn't show up in my table.
I have similar code that is implemented elsewhere and it works so I don't know why it fails in this instance.
I've tried taking out the code that references my column in the select statement so that the column isn't referenced until the ALTER TABLE ADD statement but that didn't work.
DECLARE
#Total_Good_Percent float
SELECT
COUNT(CASE WHEN HMC_Place_Position IS NULL THEN 0 END) AS Parts,
COUNT(*) AS Total_Parts,
COUNT(CASE
WHEN Outfeed_Place_Time IS NOT NULL THEN 1
END) AS Total_Good_Parts, /*Total Good Parts */
(COUNT(Total_Good_Parts)*100 / (Total_Parts))/convert(float,count(*)) AS Total_Good_Percent,
COUNT(CASE
WHEN (Reject_Place_Time IS NOT NULL AND Telesis_Stamp = '') THEN 1
END) AS Total_Rejects, /*Total Rejects */
COUNT(CASE
WHEN (HMC_Place_Position IN (13, 14)) AND (Outfeed_Place_Time IS NOT NULL) THEN 1
END) AS Total_Passed_Remeasures, /*Total Passed Remeasures */
COUNT(CASE
WHEN ((Reject_Place_Time IS NOT NULL) AND (Outfeed_Place_Time IS NULL) AND Infeed_Pick_Time IS NULL) THEN 1
END) AS Total_Failed_Remeasures /*Total Failed Rejects */
FROM PartData_GKN05_H
WHERE Infeed_Pick_Time >= DATEADD(day,-7, GETDATE()) OR (Infeed_Pick_Time is null AND (Reject_Place_Time >= DATEADD(day,-7, GETDATE()) OR Outfeed_Place_Time >= DATEADD(day,-7, GETDATE())))
GROUP BY Total_Good_Parts
ALTER TABLE PartData_GKN05_H Add Total_Passed_Remeasures int
ALTER TABLE PartData_GKN05_H Add Total_Good_Parts int
ALTER TABLE PartData_GKN05_H Add Total_Rejects int
ALTER TABLE PartData_GKN05_H Add Total_Failed_Remeasures int
ALTER TABLE PartData_GKN05_H ADD Total_Parts int
ALTER TABLE PartData_GKN05_H ADD Parts int
ALTER TABLE PartData_GKN05_H ADD Total_Good_Percent float
I also have a COUNT AS statement which I believe should create the column but it doesn't.
Related
I have a table that contains a column date, I want to add to the the same table 4 other columns DAY, MONTH, YEAR, QUARTER based on the value of the column date for all the records in the table. How could it be done please ?
Option 1 - computed columns via datepart
ALTER TABLE dbo.MyTable
ADD TheYear = DATEPART(YEAR, DateColumn);
ALTER TABLE dbo.MyTable
ADD TheQuarter = DATEPART(QUARTER, DateColumn);
ALTER TABLE dbo.MyTable
ADD TheMonth = DATEPART(MONTH, DateColumn);
ALTER TABLE dbo.MyTable
ADD TheDay = DATEPART(DAY, DateColumn);
This adds virtual, read-only columns to your table based on the value of your source column. This is likely the easiest, least approach unless you have not supplied all the relevant points.
Option 2 - Add columns
ALTER TABLE dbo.MyTable
ADD TheYear int;
ALTER TABLE dbo.MyTable
ADD TheQuarter tinyint;
ALTER TABLE dbo.MyTable
ADD TheMonth tinyint;
ALTER TABLE dbo.MyTable
ADD TheDay tinyint;
This is likely going to cause you pain as there is nothing ensuring the values stored in those 4 columns has any bearing on the value in your original Date column but it's an approach.
And since you're tagging SSIS, if you are trying to do this in a data flow - don't. Write the query to do it and bring this data into your pipeline
SELECT T.*
, TheYear = DATEPART(YEAR, T.DateColumn);
, TheQuarter = DATEPART(QUARTER, T.DateColumn);
, TheMonth = DATEPART(MONTH, T.DateColumn);
, TheDay = DATEPART(DAY, T.DateColumn);
FROM dbo.MyTable AS T;
i try to build a store procedure who insert data to a table,
after it run, the table is empty.
this is the code:
CREATE TABLE invoices
(invoiceNo int,
invoiceDate date,
invoiceTotal int,
invoiceType char(1))
alter PROCEDURE Invoices_AGG
#year int
AS
select
(case when MONTH(invoiceDate) >9 then concat('01','/',MONTH(invoiceDate),'/',year(invoiceDate)) else concat('01','/0',MONTH(invoiceDate),'/',year(invoiceDate)) end) as DateID,
SUM(case when invoiceType = 'B' then invoiceTotal else 0 end) as Total_Incomes_TypeB,
SUM(case when invoiceType = 'I' then invoiceTotal else 0 end) as Total_Incomes_TypeI
into FACT_Invoices_AGG
from invoices
where year(invoiceDate)=#year
group by (case when MONTH(invoiceDate) >9 then concat('01','/',MONTH(invoiceDate),'/',year(invoiceDate)) else concat('01','/0',MONTH(invoiceDate),'/',year(invoiceDate)) end);
exec Invoices_AGG 2013
thank you
you haven't specified the table in which you want to insert data and since your table is empty on which you are applying your select query it's returning no result.
If you want to use
into
you should also mention your code for FACT_Invoices_AGG function.
The SELECT INTO statement creates a table and fills it with data. Executing 2 or more times that statement will fail (since the table will be created on the first run and will try to create it again on the second one).
If the table is empty is either because the query returned no results, or the SP failed because of the reason I mentioned before (or even failed while building the results, for example with a bad conversion). When using SELECT INTO, make sure to drop the table IF EXISTS before (if this is what you want).
ALTER PROCEDURE Invoices_AGG
#year int
AS
BEGIN
IF EXISTS( SELECT 'table exists' FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N'FACT_Invoices_AGG'AND TABLE_SCHEMA = 'dbo')
DROP TABLE dbo.FACT_Invoices_AGG
select
(case when MONTH(invoiceDate) >9 then concat('01','/',MONTH(invoiceDate),'/',year(invoiceDate)) else concat('01','/0',MONTH(invoiceDate),'/',year(invoiceDate)) end) as DateID,
SUM(case when invoiceType = 'B' then invoiceTotal else 0 end) as Total_Incomes_TypeB,
SUM(case when invoiceType = 'I' then invoiceTotal else 0 end) as Total_Incomes_TypeI
into
FACT_Invoices_AGG
from
invoices
where
year(invoiceDate)=#year
group by
(case when MONTH(invoiceDate) >9 then concat('01','/',MONTH(invoiceDate),'/',year(invoiceDate)) else concat('01','/0',MONTH(invoiceDate),'/',year(invoiceDate)) end);
END
GO
Another option would be changing your SELECT INTO for a INSERT INTO (columnNames, ...) SELECT which requires that the table exists beforehand.
Try executing the SELECT without the INTO to see if it doesn't fail while computing the result. If it doesn't then make sure the destination table does not exist before using a SELECT INTO.
I'm creating an inventory for a restaurant using Microsoft SQL Server 2014.
This is diagram from 5 tables
I want to write a trigger for whenever I insert new order into orderDetail table, the table from inventory will auto update the outStock as orderDetail.quantity and the stockLeft based on previous stockLeft within the table that matched the product_ID.
I'm very new to SQL Server. Any opinion/suggestion would be very helpful to me. Thanks!!
Here are my table database from
inventory and orderDetail
This is what I've tried so far
USE [BuffaloWildWingsDB]
GO
CREATE TRIGGER update_stock
ON orderDetail
AFTER INSERT
AS
BEGIN
DECLARE #stock INT,#productID INT, #prevDate date, #prevStock INT;
SET #stock = (SELECT quantity FROM orderDetail)
SET #productID = (SELECT product_ID FROM orderDetail)
SET #prevDate = (SELECT [date] FROM inventory WHERE inventory.product_ID = #productID AND [date] < GETDATE())
SET #prevStock = (SELECT stockLeft FROM inventory WHERE [date] = #prevDate)
INSERT INTO inventory (product_ID, outStock, stockLeft) VALUES (#productID,#stock,#prevStock-#stock);
END
I can run this query fine but whenever I update orderDetail with
INSERT INTO orderDetail(order_ID,product_ID, quantity) values (10101, 1013, 2)
GO
I got this error
Msg 512, Level 16, State 1, Procedure update_stock, Line 14 Subquery
returned more than 1 value. This is not permitted when the subquery
follows =, !=, <, <= , >, >= or when the subquery is used as an
expression. The statement has been terminated.
Any idea?
Your trigger will only work for separate inserts only. If you will insert several rows at once it will fail. Also you are selecting from base table instead of INSERTED table. Here is what your trigger should look like:
insert into inventory (product_id, outStock, stockLeft)
select i.product_id, i.quantity, isnull(oa.stockLeft, 0) - i.quantity
from inserted i
outer apply(select top 1 stockLeft
from inventory
where product_id = i.product_id and [date] < GETDATE()
order by [date] desc)oa
I created a unique constraint as below which is working fine. But I want to create a constraint where the productNumber between the two dates should be unique
ALTER TABLE [dbo].[Product] ADD CONSTRAINT U_Product UNIQUE ([ProductNumber],[StartDate],[EndDate])
Right now, it is taking the exact value in columns, but I want it between two dates. How can I do this ?
create function dbo.IsProductUnique (#ProductNumber int, #StartDate date, #EndDate date) returns bit as
begin
if exists (
select *
from Product
where ProductNumber = #ProductNumber
and StartDate < #EndDate
and EndDate > #StartDate) return 0
else
return 1 -- Unique
end
go
alter table Product add constraint CK_Product_Unique check (dbo.IsProductUnique(ProductNumber, StartDate, EndDate) = 1)
go
I Have a table in SQL SERver with name T_ACCOUNT with 2 columns ACCOUNT_ID and CUSTOMER_ID both as int.
Now i have to read the last row of that table and insert a new row with the values of last row incrementing by 1.
How can I do this?
I tried like this
SELECT ACCOUNT_ID,CUSTOMER_ID FROM T_ACCOUNT order by ACCOUNT_ID desc
INSERT T_ACCOUNT(ACCOUNT_ID,CUSTOMER_ID)
VALUES(ACCOUNT_ID = ACCOUNT_ID + 1 AND CUSTOMER_ID = CUSTOMER_ID +1)
but it was showing the syntax error.can anyone help me
The below statement picks the last row (record with max account_id) and inserts the next row.
INSERT INTO T_ACCOUNT (ACCOUNT_ID,CUSTOMER_ID)
SELECT ACCOUNT_ID + 1, CUSTOMER_ID +1
FROM T_ACCOUNT
Where ACCOUNT_ID = (select max(ACCOUNT_ID) from T_ACCOUNT)
The where clause is used in picking the last row.
You should consider creating a column in your sql table that auto increments so you can just do an insert at end of existing records.
A very strange requirement but anyway this is how you would go about doing this....
INSERT INTO T_ACCOUNT (ACCOUNT_ID,CUSTOMER_ID)
SELECT TOP 1 ACCOUNT_ID + 1, CUSTOMER_ID +1
FROM T_ACCOUNT
ORDER BY ACCOUNT_ID desc
Order by is irrelevant here, no need for that.
You should really create a stored procedure to do this operation, Create two output parameters to get the newly created values. something like as follows
CREATE PROCEDURE dbo.Add_Record
#ACCOUNT_ID INT OUTPUT,
#CUSTOMER_ID INT OUTPUT
AS
BEGIN
SET NOCOUNT ON;
DECLARE #AccountID INT, #CustomerID INT;
SELECT TOP 1 #AccountID = ACCOUNT_ID
,#CUSTOMER_ID = CUSTOMER_ID
FROM T_ACCOUNT
ORDER BY ACCOUNT_ID DESC;
SET #AccountID = #AccountID + 1;
SET #CUSTOMER_ID = #CUSTOMER_ID + 1;
INSERT INTO T_ACCOUNT (ACCOUNT_ID,CUSTOMER_ID)
VALUES (#AccountID, #CUSTOMER_ID)
END