SQL - Must declare the scalar variable error - sql

I can't seem to figure out what is wrong with my SQL code. It says I need to declare the scalar variable #tempMile2, but it is a declared table.
INSERT INTO #tempMile (UserFullName, USERs_ID, timecard_date, timecard_createddate)
SELECT UserFullName, USERs_ID, timecard_date, timecard_createddate
FROM v_tblTimeCard
WHERE convert(date, TimeCard_CreatedDate) = dateadd(day,-1, cast(getdate() as date))
group by
userfullname,
USERs_ID,
timecard_date,
TimeCard_CreatedDate
DECLARE #tempMile2 table (USERs_ID int, timecard_date date)
INSERT INTO #tempMile2 (USERs_ID, timecard_date)
SELECT USERs_ID, timecard_date --add count logic here --timecard entries 1 for day
FROM #tempMile
group by USERs_ID, timecard_date
select * from dbo.tblMileage left join
#tempMile2 on tblMileage.Users_ID = #tempMile2.USERs_ID AND tblMileage.DateOfService = #tempMile2.timecard_date
where #tempMile2.TimeCard_Date IS NOT NULL
It is only in the last select statement where the #tempMile2 is asking to be declared.
Any thoughts?

You cannot use a table variable to qualify a column name. The table alias cannot start with #. So, try this:
select *
from dbo.tblMileage m left join
#tempMile2 tm
on m.Users_ID = tm.USERs_ID and m.DateOfService = tm.timecard_date
where tm.TimeCard_Date IS NOT NULL;
Of course, your comparison in the where clause implies that the join is an inner join, not an outer join, but I didn't make that change.

Related

How do I display the count value of the results from one column in a new column?

This stored procedure returns two values but it repeats multiple times.
I am trying to get the count value of PLTGRN so that it shows up in a new column like in this image:
My code:
ALTER PROCEDURE[dbo].[GreenTire_Fits_In_Press]
#Press varchar(10)
AS
BEGIN
SELECT FAC,PLTGRN
FROM [TireTrack].[dbo].[cos_work] cosw WITH (nolock)
INNER JOIN [DataWarehouse].[dbo].[v_Curing_Tooling] CURE WITH (Nolock) ON Cure.MLDNBR = Cosw.MOLD
WHERE Cosw.FAC = #Press
END
I tried adding COUNT(PLTGRN) in the select statement to the code above but that throws this error :
you need to use GROUP BY :
ALTER PROCEDURE[dbo].[GreenTire_Fits_In_Press]
#Press varchar(10)
AS
BEGIN
Select PLTGRN , COUNT(*) QTY
FROM [TireTrack].[dbo].[cos_work] cosw with (nolock)
Inner Join [DataWarehouse].[dbo].[v_Curing_Tooling] CURE with (Nolock)
On Cure.MLDNBR=Cosw.MOLD
Where Cosw.FAC=#Press
GROUP BY PLTGRN
End
SUM is used with a GROUP BY clause. The aggregate functions summarize the table data. Once the rows are divided into groups, the aggregate functions are applied in order to return just one value per group. It is better to identify each summary row by including the GROUP BY clause in the query result.
ALTER PROCEDURE[dbo].[GreenTire_Fits_In_Press]
#Press varchar(10)
AS
BEGIN
SELECT FAC,PLTGRN, COUNT(PLTGRN)
FROM [TireTrack].[dbo].[cos_work] cosw WITH (nolock)
INNER JOIN [DataWarehouse].[dbo].[v_Curing_Tooling] CURE WITH (Nolock) ON Cure.MLDNBR = Cosw.MOLD
WHERE Cosw.FAC = #Press
GROUP BY FAC, PLTGRN
END
-- you are missing group by and the part of the query to get count
ALTER PROCEDURE[dbo].[GreenTire_Fits_In_Press]
#Press varchar(10)
AS
BEGIN
Select FAC,PLTGRN, count(*)
FROM [TireTrack].[dbo].[cos_work] cosw with (nolock)
Inner Join [DataWarehouse].[dbo].[v_Curing_Tooling] CURE with (Nolock)
On Cure.MLDNBR=Cosw.MOLD
Where Cosw.FAC=#Press
Group By FAC,PLTGRN
End

SQL Inner Join and nearest row to date

I dont't get it. I changed some of the code. In the WPLEVENT Table are a lot of Events per person. In the Persab-Table are the Persons with their History. Now I need the from the Persab Table just that row wich matches the persab.gltab Date nearest to the WPLEVENT.vdat Date. So all rows from the WPLEVENT, but just the one matching row from the PERSAB-Table.
SELECT
persab.name,
persab.vorname,
vdat,
eventstart,
persab.rc1,
persab.rc2
FROM wplevent
INNER JOIN
persab ON WPLEVENT.PersID = persab.PRIMKEY
INNER JOIN
(SELECT TOP 1 persab.rc1
FROM PERSAB
WHERE persab.gltab <= getdate() --/ Should be wplevent.vdat instead of getdate()
) NewTable ON wplevent.persid = persab.primkey
WHERE
persid ='100458'
ORDER BY vdat DESC
Need to use the MAX() function with the proper syntax by supplying an expression like MAX(persab.rc1). Also need to use GROUP BY for the second column rc2 in the subquery (although it looks like you do not need it). Finally you are missing the ON clause for the final INNER JOIN. I can update the answer to fix the query if you provide that information.
SELECT
Z1PERS.NAME
, Z1PERS.VORNAME
, WPLEVENT.VDat
, WPLEVENT.EventStart
, WPLEVENT.EventStop
, WPLEVENT.PEPGROUP
, Z1SGRP.TXXT
, PERSAB.GLTAB
, Z1PERS.PRIMKEY AS Expr1
, PERSAB.PRIMKEY
FROM
Z1PERS
INNER JOIN
WPLEVENT ON Z1PERS.PRIMKEY = WPLEVENT.PersID
INNER JOIN
Z1SGRP ON WPLEVENT.PEPGROUP = Z1SGRP.GRUPPE
INNER JOIN
(
SELECT MAX(Persab.rc1) --Fixed MAX expression
, persab.rc2
FROM
persab
GROUP BY
persab.rc2 --Need to group on rc2 if you want that column in the query otherwise remove this AND the rc2 column from select list
WHERE
WPLEVENT.PersID = PERSAB.PRIMKEY
AND WPLEVENT.VDat <= PERSAB.GLTAB
) --Missing ON clause for the INNER JOIN here
WHERE z1pers.vorname = 'henning'

SQL: Select A when in A and not B or select B when in A and B

SQL is not my strong point and I am struggling to find a solution to this issue. I am trying to figure out how I can get a result set based on the following logic. Select record A when A is not in B OR select B if the record appears in B and A. I tried the following union which returns me all the records that match from the current day in the two tables but I cannot figure out how to pull the data I need from the two tables.
SELECT 'a',PurchaseOrderLine.iPurchaseOrderLineId, sProductDescription
FROM PurchaseOrderLine
WHERE PurchaseOrderLine.dRequiredDate = convert(date, getdate())
UNION
SELECT 'b',PurchaseOrderLine.iPurchaseOrderLineId, sProductDescription
FROM GoodsIn
INNER JOIN PurchaseOrderLine
ON PurchaseOrderLine.iPurchaseOrderLineId = GoodsIn.iPurchaseOrderLineId
WHERE GoodsIn.dDateDelivered = getdate())
You can do a left outer join, and use a ISNULL or CASE statement in the select to return the required values.
I'll demonstrate:
SELECT
CASE WHEN b.iPurchaseOrderLineId IS NOT NULL THEN 'b' ELSE 'a' END AS [Source],
a.iPurchaseOrderLineId,
ISNULL(b.sProductDescription, a.sProductDescription) AS [sProductDescription]
FROM PurchaseOrderLine AS a
LEFT JOIN GoodsIn AS b ON a.iPurchaseOrderLineId = b.iPurchaseOrderLineId
AND b.dDateDelivered = GETDATE()
WHERE b.iPurchaseOrderLineId IS NOT NULL
OR a.dRequiredDate = CONVERT(DATE, GETDATE())
Hope that helps!
Hope This will help You: Just an example similar to you.
create table A(id int , name char(12))
go
create table B(id int , name char(12))
go
insert into A values (1,'ABC'),(3,'WXY')
insert into B values (1,'ABC'),(2,'AAA')
SELECT a.id,a.name FROM A EXCEPT SELECT * FROM B
UNION
SELECT a.id,a.name FROM A inner join b on a.id=b.id and a.name=b.name
Thanks!!!
If I understand you correctly, assuming GoodsIn=B, you may try something in this fashion.
SELECT 'a',PurchaseOrderLine.iPurchaseOrderLineId, sProductDescription
FROM PurchaseOrderLine
LEFT JOIN GoodsIn
ON PurchaseOrderLine.iPurchaseOrderLineId = GoodsIn.iPurchaseOrderLineId
WHERE PurchaseOrderLine.dRequiredDate = convert(date, getdate())
AND GoodsIn.iPurchaseOrderLineId IS NULL
UNION
SELECT 'b',PurchaseOrderLine.iPurchaseOrderLineId, sProductDescription
FROM GoodsIn
INNER JOIN PurchaseOrderLine
ON PurchaseOrderLine.iPurchaseOrderLineId = GoodsIn.iPurchaseOrderLineId
WHERE GoodsIn.dDateDelivered = getdate());
You could also try literally as you described (assuming sProductDescription is in PurchaseOrderLine):
"Select record A when A is not in B"
SELECT 'a',PurchaseOrderLine.iPurchaseOrderLineId, sProductDescription
FROM PurchaseOrderLine
WHERE iPurchaseOrderLineId NOT IN(SELECT iPurchaseOrderLineId FROM GoodsIn)
or in this way:
SELECT 'a',PurchaseOrderLine.iPurchaseOrderLineId, sProductDescription
FROM PurchaseOrderLine
WHERE NOT EXISTS(SELECT * FROM GoodsIn
WHERE GoodsIn.iPurchaseOrderLineId=PurchaseOrderLine.iPurchaseOrderLineId)
or using EXCEPT:
SELECT 'a',PurchaseOrderLine.iPurchaseOrderLineId, sProductDescription
FROM PurchaseOrderLine
EXCEPT
SELECT 'a', iPurchaseOrderLineId, sProductDescription
FROM GoodsIn;
Just hints, tailor them to your needs.

Move data from SQL results to existing table

I'm a little bit stuck. I have a database table with the following columns:
Table Name: Data
*Value
*DateTime
*WeekNumber
*ItemId
*Name
I have created the following scripts from which I'd like to place the results into the above table.
SELECT D.*, M.Name
FROM
(SELECT SUM (Data) AS [Value],
(SELECT CONVERT(Date,DATEADD(week,-1,GETDATE()))) [DateTimeValue], DatePart (Week,TimestampUTC) [WeekNumber], MT.MeterId [MeterID]
FROM DataLog.dl
JOIN MeterTags mt ON dl.MeterTagId = mt.MeterTagId
GROUP BY DatePart (Week,TimestampUTC, dl.MeterTagId, MeterId)
AS D
INNER JOIN Meters m
ON D.MeterId = M.MeterId
ORDER BY MeterId DESC
I'm hoping to drop the results from the above query into the corresponding columns in the db table along with creating a new one for MeterID:
Value = Value
DateTime = DateTimeValue
WeekNumber = WeekNumber
MeterID = ***Need to create a new column*****
Name = Name
I hope this makes sense as I'm pretty inexperienced with SQL and a struggling to get the last pieces put together. Any help you can give would be greatly appreciated.
Thanks.
you can use the standard SQL INSERT syntax
INSERT INTO table2
SELECT * FROM table1;
what i don't understand is what do you mean by
MeterID = Need to create a new column**
for more info look
http://www.w3schools.com/sql/sql_insert_into_select.asp and
http://msdn.microsoft.com/en-us/library/ms188263(v=sql.105).aspx
Modify your table and add new column for MeterId.
Insert into [Data]
SELECT D.[Value], D.DateTimeValue,D.WeekNumber,MT.MeterId,M.Name
FROM
(SELECT SUM (Data) AS [Value],
(SELECT CONVERT(Date,DATEADD(week,-1,GETDATE()))) [DateTimeValue], DatePart (Week,TimestampUTC) [WeekNumber], MT.MeterId [MeterID]
FROM DataLog.dl
JOIN MeterTags mt ON dl.MeterTagId = mt.MeterTagId
GROUP BY DatePart (Week,TimestampUTC, dl.MeterTagId, MeterId)
AS D
INNER JOIN Meters m
ON D.MeterId = M.MeterId
ORDER BY MeterId DESC

Query, subquery and using as variables from subquery

Is it not possible to use the "as [item] and then use the item variable in the query.
For example:
select c.category as [category],c.orderby as [CatOrder], m.masterno, m.master
,-- select OUT (select count(*) from rentalitem ri with (nolock),
rentalitemstatus ris with (nolock),
rentalstatus rs with (nolock)
where ri.rentalitemid = ris.rentalitemid
and ris.rentalstatusid = rs.rentalstatusid
and ri.masterid = m.masterid
and rs.statustype in ('OUT', 'INTRANSIT', 'ONTRUCK')) as [qtyout]
,-- select OWNED owned=
(select top 1 mwq.qty
from masterwhqty mwq
where mwq.masterid = m.masterid)
, -([owned]-[qtyout]) as [Variance]
from master m
inner join category c on c.categoryid=m.categoryid and c.categoryid=#category
inner join inventorydepartment d on c.inventorydepartment=#department
I cannot seem to use qtyout or owned when calculating variance. How can I do that?
You can also use a table variable and then reference that table variable like you are trying to do above....here's an example from MSDN
USE AdventureWorks2012;
GO
DECLARE #MyTableVar table(
EmpID int NOT NULL,
OldVacationHours int,
NewVacationHours int,
ModifiedDate datetime);
UPDATE TOP (10) HumanResources.Employee
SET VacationHours = VacationHours * 1.25,
ModifiedDate = GETDATE()
OUTPUT inserted.BusinessEntityID,
deleted.VacationHours,
inserted.VacationHours,
inserted.ModifiedDate
INTO #MyTableVar;
--Display the result set of the table variable.
SELECT EmpID, OldVacationHours, NewVacationHours, ModifiedDate
FROM #MyTableVar;
GO
--Display the result set of the table.
SELECT TOP (10) BusinessEntityID, VacationHours, ModifiedDate
FROM HumanResources.Employee;
GO
need to move your calculated fields into a subquery, and then use them by their alias in the outer query.
select subquery.*, -([owned]-[qtyout]) as [Variance]
from
(
select c.category as [category],c.orderby as [CatOrder], m.masterno, m.master
,-- select OUT (select count(*) from rentalitem ri with (nolock),
rentalitemstatus ris with (nolock),
rentalstatus rs with (nolock)
where ri.rentalitemid = ris.rentalitemid
and ris.rentalstatusid = rs.rentalstatusid
and ri.masterid = m.masterid
and rs.statustype in ('OUT', 'INTRANSIT', 'ONTRUCK')) as [qtyout]
,-- select OWNED owned=
(select top 1 mwq.qty
from masterwhqty mwq
where mwq.masterid = m.masterid) as [owned]
from master m
inner join category c on c.categoryid=m.categoryid and c.categoryid=#category
inner join inventorydepartment d on c.inventorydepartment=#department
) as subquery
YOu need to use a subquery:
select t.*,
([owned]-[qtyout]) as [Variance]
from (<something like your query here
) t
You query, even without the comments, doesn't quite make sense (select OUT (select . . . for isntance). But, the answer to your question is to define the base variables in a subquery or CTE and then subsequently use them.
And, you are calling the difference "variance". Just so you know, you are redefining the statistical meaning of the term (http://en.wikipedia.org/wiki/Variance), which is based on the squares of the differences.