Need a MySQL workaround to pass a variable \ parameter into view? - mysql

I would like to pass a variable\parameter into a view to filter by a date range. Since I am doing grouping in the view I can not put the where clause externally to the view.
I have read a bunch of posts on this but have not been able to get it working yet. Most workaround I have seen to pass a parameter into a view involve using a function to return the value and this is where I am getting stuck.
/* My current view that I want to pass in start and end dates */
CREATE VIEW Total_Sales_By_Product_Num AS
SELECT products_all_fields.*,
Sum(<a bunch of code removed for this sample>) AS Item_Qty_Requested_Total,
Sum(<a bunch of code removed for this sample>) AS Item_Qty_Accepted_Total,
Sum(<a bunch of code removed for this sample>) AS Total_Sales_Dollars
FROM products_all_fields
LEFT OUTER JOIN (web_orders_items
INNER JOIN web_orders_header
ON web_orders_items.Web_Order_Num = web_orders_header.Web_Order_Num )
ON products_all_fields.Product_Num = web_orders_items.Product_Num
WHERE web_orders_header.Order_Date BETWEEN fn_GetStartDate() AND fn_GetEndDate()
GROUP BY products_all_fields.Product_Num
ORDER BY products_all_fields.Description
The functions to return the parameters to the view:
CREATE FUNCTION fn_GetStartDate ()
RETURNS DATE
DETERMINISTIC NO SQL
BEGIN
RETURN #StartDate;
END
CREATE FUNCTION fn_GetEndDate ()
RETURNS DATE
DETERMINISTIC NO SQL
BEGIN
RETURN #EndDate;
END
This does not work, it returns no data, I know I am doing something stupid
set #fn_StartDate := '2012-01-01';
set #fn_EndDate := '2012-02-01';
select * from Total_Sales_By_Product_Num
Thanks for any help!

Ahhh!!! I got it working, I feel like an idiot but I had double quotes not single quotes in one of my assignments of the dates. It seems to work now. I will leave this post up for future people searching how to do this.

It should be work as below:
set #StartDate := '2012-01-01';
set #EndDate := '2012-02-01';
select * from Total_Sales_By_Product_Num;

You need
SET #fn_StartDate = fn_GetStartDate('2012-01-01')
same with #fn_EndDate
and then in your view
WHERE web_orders_header.Order_Date BETWEEN #fn_StartDate.....
However, that's just the syntax of how to call a function. You're still trying to pass a parameter to a view, which is not possible, as far as I know. Try putting all your View logic in the function instead.

Related

MySQL multiquery gives errors, need to save variable

I have a table where I need to do two selections. First I need to find OBJ where uunn = abc. Then I need to select where OBJ equals the first result but it doesn't work.
Example:
SELECT OBJ INTO #obj FROM wddt WHERE `uunn`='abc' AND `mqr`='ps';
SELECT mqr FROM wddt WHERE `OBJ` = #obj AND `uunn`='as';
My goal is to check if mqr has a certain content, and I will compare that content in my PHP script.
Multi_query was disabled on the server I was trying to use, just tested everything using XAMPP and works like a charm. I didn't know multi-query could be disabled.
If you don't need the actual results of the first query you may use a subquery in the WHERE clause of the second one:
SELECT mqr FROM wddt WHERE `uunn`='as'
AND `OBJ` LIKE (SELECT OBJ FROM wddt WHERE `uunn`='abc' AND `mqr`='ps');

Statement in trigger is not "picking up" the condition in its Where clause

so I'm currently working on a MySQL trigger. I'm trying to assign values to two variables when a new record is inserted. Below are the queries:
SET mssgDocNo = (SELECT Document_ID FROM CORE_MSSG WHERE Message_ID = new.MSSG_ID);
SET mssgRegime = (SELECT CONCAT (Regime_Type, Regime_Code) FROM T_DOC WHERE CD_Message_ID = new.MSSG_ID);;
For some reason, the second SQL query is not picking up the 'new.MSSG_ID' condition while the first query in same trigger recognizes it. I really can't figure out what seems to be the problem.
When I replace the 'new.MSSG_ID' with a hard-coded value from the database in the second query it seems to work. I doubt the 'new.MSSG_ID' is the problem because it works perfectly fine in the first query.
I've tried pretty much anything I could think of. Would appreciate the help.
I would write these more simply as:
SELECT mssgDocNo := Document_ID
FROM CORE_MSSG
WHERE Message_ID = new.MSSG_ID;
SELECT mssgRegime := CONCAT(Regime_Type, Regime_Code)
FROM T_DOC
WHERE CD_Message_ID = new.MSSG_ID;
The SET is not necessary.
I did make one other change that might make it work. I removed the space after CONCAT. Some versions of MySQL have trouble parsing spaces after function calls.

How to call MySQL Function within the Query, so that query can use the session variable set in the function?

SELECT s.* FROM (SELECT setUserId('abcd123') p) tmp_p, main_article_view s
The problem is that the function setUserId(userId char(36)) in MySQL set a session variable, that is being used in main_article_view; the first time I run this query, it does not work, because the function gets executed in the end.
But when I run it second time, it does works perfectly; because was set previously on first run in session.
The limitation for me is that I cannot use the simple := operator to set the userIdParam (session variable) in NHibernate; because NHibernate uses : for named parameters.
The below query works, but it is not working as I said with NHibernate.
SELECT s.* FROM (SELECT #userIdParam:='abc123' p) tmp_param, main_article_view s
The workaround I am doing right-now is calling first the function setUserId() and then calling the actual query alone like select * from main_article_view, which works, but then there will be two calls, which I don't like.
Actually I just want to use View with parameter; so any suggestions would be welcomed?
Thanks & Regards

Using a scalar valued find string function when searching multiple rows returned?

Given SQL Server 2008, I have written a simple find in string function as follows:
ALTER FUNCTION [dbo].[FindInString]
(
#FindText VARCHAR(255),
#TextSource VARCHAR(512)
)
RETURNS INT
AS
BEGIN
DECLARE #Result INT
SET #Result = 0
SELECT #Result = CHARINDEX(#FindText, #TextSource)
RETURN #Result
END
The complexity of the find function may change in the future, which is why I wanted to encapsulate it in a function.
Now, when I only have one matching record in a table, this works:
SELECT #FindCount = dbo.FindInString('somestring', (SELECT TableSearch FROM Segments WHERE CID=22793))
However, when the select statement returns more than one, it makes sense as to why an error is thrown.
like to know is what I need to do to still have this work as a simple call, as above?
I only need to know if there is one match (I just need to know if #FindCount > 0), and I'm guessing some sort of a loop may be required, but would like to keep this as simple as possible.
Thanks.
You can use aggregate functions and one select:
select
#FindCount = sum(dbo.FindInString('somestring', TableSearch))
from
Segment
where
CID = 22793
Just take care with this, as FindInString will fire for each row, which can significantly reduce query performance. In this case, it's the only way to solve your problem, but just beware of the troubles that could arise.

Parameters in SQL Server 2008

I have a stored procedure that pulls data for a report. I'm having a problem with the parameters. I have a couple temp tables and some joins that work so I have omitted them below. The problem is this line:
WHERE
SeminarDivision = #SeminarDivision AND SeminarType = #SeminarType
When I put this where clause in to use my seminar parameters the stored proc returns nothing But I need to generate a report based on those two parameters. So where do the parameters go? Can anyone help?
#StartDate DateTime,
#EndDate DateTime,
#SeminarDivision VARCHAR(50),
#SeminarType VARCHAR(50)
)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
... OMITTED
SELECT
WL.PID,
CONVERT(varchar(20), upper(substring(FirstName,1,1))+
LOWER(substring(FirstName,2,19))) AS FirstName,
CONVERT(varchar(20), upper(substring(LastName,1,1))+
LOWER(substring(LastName,2,19))) AS LastName,
S.SeminarDivision,
S.SeminarType,
S.StartDate,
S.SeminarLocation
FROM
#tblWaitList WL
INNER JOIN #tblSeminar S ON WL.SeminarGuid=S.SeminarGuid
WHERE
SeminarDivision = #SeminarDivision AND SeminarType = #SeminarType
ORDER BY
LastName,FirstName,StartDate
First and foremost there is nothing wrong with your code, when asking where do these parameters go, they go exactly where you put them. The question is - is the data coming in for SeminarDivision and SeminarType the right type of data? For instance just as a test,
copy the code into a new sql code query inside the editor. Run the command without the where, if you get values great. Now change the where to
WHERE
SeminarDivision = "Possible_Value"
Where Possible_Value should be a possible value...If it returns rows, good...now add the second condition also hardcoding a value:
WHERE SeminarDivision = "Possble_Value" AND SeminarType="Possible_Value_2"
Getting any data? Is it possible you want OR rather then AND ?
There's nothing wrong with the 'location' of your params.
If you're getting no data back, it's either because you've not populated #tblWaiList or #tblSeminar or because the records simply don't match your WHERE clause.
Check your params have the value you think they do by executing print #SeminarDivision etc.
SELECT * FROM #tblSeminar may give you a clue too.
You are not setting parameters correctly for the call.
Try this in SSMS, change values accordingly
EXEC Proc '20110101', '20111101', 'PossibleDivision', 'PossibleType'
If this fails, then show us "OMITTED" code
if this works, show us how you are calling this from the client code