While I am execution the following procedure I get these errors:
Must declare the scalar variable "#USer_Id".
Must declare the scalar variable "#Activity".
Can anybody help me how to fix these errors?
Here is the view creation is mandatory and the conditions are initially the view table data should be retrieved based upon the User_Id, given Timestamp rage i.e. start_time and end_time parameters and after getting the result, we have get the data based upon the Activity
The code which I wrote
create procedure Proc1
#User_Id varchar(50),
#start_time bigint,
#end_time bigint,
#view_name varchar(50),
#Activity varchar(30)
as
begin
exec('create view view_name
as
select
Asset_Id, Activity, User_Id, Event_Description, Timestamp
from
(SELECT
[j30c_editorial_id] AS Asset_Id,
[j30c_action] As Activity,
[j30c_description] As Event_Description,
[j30c_user_name] As User_Id,
[j30c_date] As Timestamp
FROM
[sandboxmbdb].[dbo].[j30t_changelog]
UNION ALL
SELECT
[Asset_Id],
[j30c_action],
[Event_Type_Desc],
[User_Id],
[Timestamp]
FROM
[refauditdatabase].[dbo].[AS_Event_Tracker_T] a,
[refauditdatabase].[dbo].[AS_Event_Type_M] b
WHERE
a.[Event_Type_Id] = b.[Event_Type_Id]) aa
where
User_Id = #User_Id
and Timestamp between #start_time and #end_time
and view_name = #view_name')
exec('select * from view_name where Activity = #Activity and view_name = #view_name')
end
Related
I have a query that works outside of a stored procedure (populate dejan_output table), but inside it doesn't. Why?
CREATE DEFINER=`admin`#`%` PROCEDURE `test_sp`()
BEGIN
declare avg_all double;
declare Zipcode text(10);
declare from1, to1, from2, to2, from3, to3, from4, to4 int;
declare Year smallint;
#######################################################################
#create output table here
DROP TABLE IF EXISTS dejan_output;
CREATE TABLE dejan_output(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
Zipcode text(10),
year smallint,
month tinyint,
RevenueIn1000USD decimal(15,4),
calendarData tinyint,
processed bit
);
#######################################################################
#insert into output table here
insert into dejan_output(Zipcode, year, month, RevenueIn1000USD, processed)
select f.Zipcode, year(ReportingMonth) year, month(ReportingMonth) month, round(sum(RevenueUSD) / 1000, 4) value, 0
from monthly_performance_data f join
(
select Zipcode, year(ReportingMonth) year, count(distinct month(ReportingMonth)) count
from monthly_performance_data
group by Zipcode, year(ReportingMonth)
) d on f.Zipcode = d.Zipcode and year(ReportingMonth) = d.year and d.count = 12
group by f.Zipcode, year(ReportingMonth) , month(ReportingMonth)
order by f.Zipcode, year(ReportingMonth) , month(ReportingMonth);
END
The table is created successfully but without any data. I am running it from MySQL Workbench 8.0.
I've found what was causing this but I still don't know why? Still, I will publish my solution so someone else can follow. Just remove any declarations:
declare avg_all double;
declare Zipcode text(10);
declare from1, to1, from2, to2, from3, to3, from4, to4 int;
declare Year smallint;
Because you can use
set #Zipcode = 'some value'
to set that variable.
I'm having trouble getting the FETCH statement to work correctly in the code below. It's actually not putting any data into the variable registerName. registerName has the same value as it has before the FETCH statement. Thanks!
-- Declare variables/cursors needed for building pivot query
DECLARE qry VARCHAR(8000);
DECLARE registerName VARCHAR(128) DEFAULT '';
DECLARE done BOOLEAN DEFAULT 0;
DECLARE registers CURSOR
FOR
SELECT RegisterName
FROM Register r
INNER JOIN EgaugeDevice ed ON ed.id = r.EgaugeDeviceId
INNER JOIN Site s ON s.id = ed.SiteId
INNER JOIN Facility f ON f.id = s.FacilityId
WHERE ShowInSite = 1 AND FacilityName = FACILITY;
DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done=1;
-- Use temporary table to get results from instantaneous view
CREATE TEMPORARY TABLE IF NOT EXISTS instData (
id INT,
RegisterId INT,
InstantaneousValue BIGINT,
Date_Time DATETIME,
Time_Stamp BIGINT
);
TRUNCATE TABLE instData;
INSERT INTO instData(id, RegisterId, InstantaneousValue, Date_Time, Time_Stamp)
SELECT id, RegisterId, InstantaneousValue, Date_Time, Time_Stamp
FROM vRegisterDataInstantaneous
WHERE Date_Time >= now() - INTERVAL 1 DAY
ORDER BY Time_Stamp DESC;
-- build pivot query from registers listed in Register table
OPEN registers;
FETCH registers INTO registerName;
select registerName AS Test;
CLOSE registers;
Is it possible to not have the same name for the column and the variable RegisterName? This could be causing a conflict, Local Variable Scope and Resolution
I have a stored procedure that I am working on that is returning an invalid return when I try to pass parameters to it compared to when I run it with hard-coded values.
Procedure with hard coded values:
BEGIN
SELECT COUNT(DISTINCT ItemID)
FROM (
SELECT *
FROM sandbox_inventoryitempurchase
WHERE OrgID = '2781823'
AND PurchaseMonth>'2015-03-01'
) as DistinctCount;
END
When run, this returns: 16 which is correct.
Procedure with two input parameters:
BEGIN
SELECT COUNT(DISTINCT ItemID)
FROM (
SELECT *
FROM sandbox_inventoryitempurchase
WHERE OrgID = orgid
AND PurchaseMonth>sincedate
) as DistinctCount;
END
The input parameters are defined as:
IN userid integer,IN orgid integer,IN sincedate date
When run, this returns: 334 which is not correct.
I am new to stored procedures and would appreciate any assistance offered regarding what I am doing wrong and what I need to do to resolve?
Thanks...
add "#" before your parameters:
BEGIN
SELECT COUNT(DISTINCT ItemID)
FROM (
SELECT *
FROM sandbox_inventoryitempurchase
WHERE OrgID = #orgid
AND PurchaseMonth>#sincedate
) as DistinctCount;
END
a fast turtorial will be: Write-a-Stored-Procedure-in-SQL
(see how to use parameters at the end of this page...)
Try using input parameters that are not the same name as your columns.
Change:
BEGIN
SELECT COUNT(DISTINCT ItemID)
FROM (
SELECT *
FROM sandbox_inventoryitempurchase
WHERE OrgID = orgid
AND PurchaseMonth>sincedate
) as DistinctCount;
END
To:
BEGIN
SELECT COUNT(DISTINCT ItemID)
FROM (
SELECT *
FROM sandbox_inventoryitempurchase
WHERE OrgID = p_orgid
AND PurchaseMonth > p_sincedate
) as DistinctCount;
END
And pass IN p_orgid integer,IN p_sincedate date
The parser may be seeing WHERE OrgID = orgid and that evaluates to true for every record since it evaluates as an identity (comparing against itself).
Param Name and field name must be different!
BEGIN
SELECT COUNT(DISTINCT ItemID)
FROM (
SELECT *
FROM sandbox_inventoryitempurchase
WHERE OrgID = p_orgid
AND PurchaseMonth > p_sincedate
) as DistinctCount;
END
I am new to Mysql. I have a stored procedure,below is my SP
CREATE DEFINER=`root`#`localhost` PROCEDURE `insertGroup`(IN startdate date,
IN enddate date,
IN amount int,
IN groupname char(50))
BEGIN
DECLARE c_id INT;
set c_id =(select id from c_begin where startdate = startdate and enddate = enddate and amount = amount);
insert into c_group (c_beginid,Groupname)
select * from (select c_id,groupname) as temp
where not exists (
select c_beginid,groupname from c_group where c_beginid = c_id and groupname = groupname
) ;
END
I am calling it like
call insertGroup ('2014-01-01','2015-12-31',100000,'GroupD');
But it is not inserting any row. I am trying to insert into "c_group" if the c_beginid and groupname is not exists.
But when i try like below
insert into c_group (c_beginid,Groupname)
select * from (select 1,'GroupD') as temp
where not exists (
select c_beginid,groupname from c_group where c_beginid = 1 and groupname = 'GroupD'
) limit 1 ;
it is working.
So What went wrong in my "insertGroup" SP. Can any one help me ?
Thanks ,
Rename your input parameter to make it clear to the DB engine when you mean the parameter and when the column name.
where startdate = startdate and enddate = enddate and amount = amount
is always true since the engine thinks you compare a column to itself.
SQL Server 2008
This is a continuation of my last question. Now I'm trying to create a stored procedure, however I can't execute it. When I execute it, an error message displays
"Cannot drop the table #MyReport", because it does not exist or you do not have permissions.
Please guide me in the right direction.
Below is my stored Procedure
Create PROCEDURE [dbo].[SEL_MyReport]
(
#employeeid int,
#date1 datetime,
#date2 datetime
)
AS
BEGIN
drop table #MyReport
Create Table #MyReport
(
employeeid int,
name varchar(30),
department varchar(30),
checkTime datetime
)
if (#employeeid > 0)
Begin
INSERT INTO #MyReport (employeeid,name, department, checkTime)
select emp.EmpolyeeID, emp.Name,dep.DeptName,tm.checkTime
from TimeInOut tm
left join Employee emp on emp.EmpolyeeId = tm.EmployeeId
left join Department dep on dep.DeptID = emp.defaultDeptID
where (DATEDIFF(s,#date1,tm.checktime) >=0
and DATEDIFF(s,#date2,tm.checktime)<=0) and emp.employeeID = #employeeid
SELECT
employeeid
,name
,department
,[Time In] = MIN(checkTime)
,[Time Out] = MAX(checkTime)
FROM #MyReport
GROUP BY employeeid,name, department, CAST(checktime AS DATE)
End
Else
Begin
INSERT INTO #MyReport (employeeid,name, department, checkTime)
select emp.EmpolyeeID, emp.Name,dep.DeptName,tm.checkTime
from TimeInOut tm
left join Employee emp on emp.EmpolyeeId = tm.EmployeeId
left join Department dep on dep.DeptID = emp.defaultDeptID
where (DATEDIFF(s,#date1,tm.checktime) >=0
and DATEDIFF(s,#date2,tm.checktime)<=0)
SELECT
employeeid
,name
,department
,[Time In] = MIN(checkTime)
,[Time Out] = MAX(checkTime)
FROM #MyReport
GROUP BY employeeid,name, department, CAST(checktime AS DATE)
End
END
Go
exec SEL_MyReport('639','05/01/2014','05/08/2014')
There is quite a bit I would change - here is the code.
You will notice
branching logic (if #employeeid > 0) has been replaced by a slightly more verbose WHERE clause
no need for #tables as far as I can tell, the SELECT should suffice
Unfortunately, I do not have anything to test against, but you should understand the general impression of it.
Further, your date filtering seemed quite strange, so I assumed you may have meant something else - I could be mistaken. Either way, the way the date filtering is now done is SARGable
CREATE PROCEDURE [dbo].[SEL_MyReport]
(
#employeeid INT,
#date1 DATETIME,
#date2 DATETIME
)
AS
BEGIN
SET NOCOUNT ON;
SELECT emp.EmpolyeeID
,emp.Name
,dep.DeptName
,[Time In] = MIN(tm.checkTime)
,[Time Out] = MAX(tm.checkTime)
FROM TimeInOut tm
LEFT
JOIN Employee emp on emp.EmpolyeeId = tm.EmployeeId
LEFT
JOIN Department dep on dep.DeptID = emp.defaultDeptID
WHERE tm.checktime >= #date1
AND tm.checktime <= #date2
/***********************************************************************************************************
* I've assumed what you may be trying to express, above
* You might also want to look at the BETWEEN() operator, remembering that it is inclusive in its behaviour
* (DATEDIFF(s,#date1,tm.checktime) >=0
* AND DATEDIFF(s,#date2,tm.checktime)<=0)
***********************************************************************************************************/
AND (emp.employeeID = #employeeid OR #employeeid <= 0)
GROUP BY emp.EmpolyeeID, emp.name, dep.department, CAST(tm.checktime AS DATE)
END
GO
Well, since the very first step of your Stored Procedure attempts to drop a table, this will obviously result in an error if that table does not exist.
To work around this, make sure you check whether the table exists, before you drop it:
IF OBJECT_ID('tempdb..#MyReport') IS NOT NULL DROP
TABLE #MyReport