declare variable in sql (hive) - sql

I had a deep look on the internet, but I'm not able to find any suitable answer.
In hive, is it possible to declare a variable, lets say:
test = 1
And change the value of this variable inside a query?
select
case
when field > 1 then test = test+1
else test = 1
end as test
from my table

It is possible. Please find the below code to create a variable in Hive.
hive> SET cust_id = 1234567890;
Once you create variable you can use it in your query like below.
hive> select * from cust_table where customer_id = '${hiveconf:cust_id}';
Hope this will help you.
Now you can apply this to your scenario.

Related

Run Hive Script with variable - problem with passing variable

I'm using DBVisualiser to run the following script (Expecting to pass variable in query and retrieve data based on where condition)
set Id='1';
select * from MyTable where account_id = '${hivevar:Id}' limit 5
Unfortunatelly, when I run this script I see that query which is executed is as follows:
set Id='1';
select * from mytable where account_id = '${hivevar:Id}' limit 5
But when I run query with hardcoded value
select * from mytable where account_id = '1' limit 5
then I get expected dataset.
I would apprecaie if anyone could help me to learn what I do wrong.
Thanks in advance.
Variables which were set without namespace are hiveconf variables, not hivevar. Though you can specify the namespace explicitly.
Try this:
set Id=1; --No need to quote here if it is quoted in the select
-- use hiveconf
select * from MyTable where account_id = '${hiveconf:Id}' limit 5;
Or this:
--specify the namespace
set hivevar:Id=1;
select * from MyTable where account_id = '${hivevar:Id}' limit 5;
See also similar question.

How do I run selected SQL queries with variables included?

I want to be able to run a snippet of my SQL query by selecting it and pressing F5. Issue is, if that selection contains a variable name I get an error: Must declare the scalar variable "#variableName".. Is there anyway to resolve this? I want variableName to be the value it would otherwise be had I run the whole statement at that moment in time that I've selected...
Sample of full code:
DECLARE #cat INT;
SET #cat = 2;
SELECT * FROM TableName
WHERE ColumnName = #cat;
Sample of my selection that I want to run without including declaration/set lines:
SELECT * FROM TableName
WHERE ColumnName = #cat;
Probably not possible but I figured it'd be worth a shot.
P.S. I'm a SQL noobie so if I'm missing something obvious let me know!
I understand where you are coming from. This is a snippet in a long procedure or something and naturally you want to keep the declarations at the top, which I agree with. In this case, when you are testing, the only real way to circumvent this is to re-declare it and set it at the top of your snippet. Then, when you are running the entire batch of code just comment out this line. Otherwise you'd have to wrap the snippet in a try / catch block to try and catch compile errors which is tricky.
Also, this is usually how I've seen people put a select * from someWorkTable to test results along the way. Then it's commented out when the batch is ran.
Left click on table name, right click design and you are able to view the datatype of the column name.
if it is nvarchar..
DECLARE #cat INT;
SET #cat = 2;
Convert(varchar, #cat)
SELECT * FROM TableName
WHERE ColumnName = #cat;
OR
directly declare
DECLARE #Cat VARCHAR(3)
SET #cat = '2'
SELECT * FROM TableName
WHERE ColumnName = #cat;
Hope this helps
You can simulate your variable as declared in a select query with an alias result. Then you can just use alias.column as part of your join...
SELECT
TN.*
FROM
( select '2' as TmpColumn ) tmpAlias
JOIN TableName TN
on tmpAlias.TmpColumn = TN.ColumnName
this way, no "scalar" variable is required, but not as practical as a simple parameterized query using a direct WHERE clause. Additionally, you could use the alias.column throughout in case you had other tables relations, etc or even additional "variables" you wanted to apply in your query.

SQL Set variable to select result

I was wondering if it is possible to set a declared variable to a return value from a select result? Something like:
#WatchedSeconds
SET #WatchedSeconds = 200
DECLARE #SelectedVideo int
SET #SelectedVideo = (SELECT TOP 1 * FROM Video v WHERE v.VideoID = 12)
IF #SelectedVideo IS NOT NULL
BEGIN
IF #SelectedVideo.VideoLength = #WatchedSeconds
BEGIN
--DO SOMETHING
END
IF #SelectedVideo.SomeOtherColumn = #SomethingElse
BEGIN
END
END
It's for using some information from the SELECT result multiple places in a Stored Procedure.
I know that I can set a variable to e.g, a integer, and set it to the selected result, if it returns a integer, e.g:
DECLARE #VideoSeconds int
SET #VideoSeconds = (SELECT v.Length FROM Video v WHERE v.VideoID = #VideoID)
This way I have to make multiple variables, and multiple SELECT calls if I need to use more values from the Video result. And that's what I want to avoid.
You can do this simply by running:
SELECT #videoSeconds = v.Length FROM Video v WHERE v.VideoID = #VideoID
so as to not add the SET part.
Also, you must make sure that only 1 row is being returned by the query, otherwise it will generate an error.
You can try something like
(declare variables first...)
SELECT TOP 1 #var1=col1, #var2=col2, #var3=col3, [...] FROM YourTable WHERE YourFilter
EDIT: All together this seems not to be the best approach... With SQL you should not think in values and single rows but rather in result sets (set based programming). Your thinking leads to many tiny selects, while loops, cursors and all this stuff one should avoid.
You can store the results in a temporary table or table variable:
SELECT TOP 1 *
INTO #SelectedVideo
FROM Video v
WHERE v.VideoID = 12;
Then you can assign values from the table later in your code. Something like:
IF ( (SELECT VideoLength FROM #SelectedVideo) = #WatchedSeconds)
However, for your particular example, if you have an index on video(VideoId), then there is little to be gained performance-wise from using a temporary table.
If what you're trying to get is similar to returning a dataset in a procedural language (so you can type something like Result.Field1 = 'Test') then I don't think this is possible. You'll just need to declare multiple variables and make the SELECT call as
SELECT TOP 1 #var1=col1, #var2=col2, #var3=col3, [...] FROM YourTable WHERE YourFilter
as #Shnugo suggests
The 'dataset' equivalent structure in SQL is cursors, but they require variables to be set up as well, so there's no benefit there.

How to use If/Else or Case statement for a checkbox with in a Select Query in SQL

I have a check box on front end.
If the check box is checked: data with only checked chk1 should appear on front end.
If the check box is not checked: full data should appear on front end.
Please suggest how should I proceed with the same in SQL Using If else / Case statement.
I am using:
SELECT *
FROM table1
where (some conditions) AND
CASE #a.Id_Oem_Irm
WHEN 0 THEN (a.id_oem_irm in(0,1))
WHEN 1 THEN (a.id_oem_irm in (1))
END
PS: a.Id_Oem_Irm: a is the table name, Id_oem_irm is the column name for check box.
I would recommend writing this as:
where (some conditions) AND
((#a.Id_Oem_Irm = 0 and a.id_oem_irm in(0, 1)) OR
(#a.Id_Oem_Irm = 1 and a.id_oem_irm in (1) )
)
I am not sure what #a.Id_Oem_Irm is supposed to be. I suspect you want a variable there.
Or you could tune it a bit like this:
SELECT *
FROM table1
where (some conditions) AND
(a.id_oem_irm = 1 OR
#a.Id_Oem_Irm = 0)
This is only valid if #a.Id_Oem_Irm is always 0 or 1. Otherwise, you obviously should add a #a.Id_Oem_Irm IN (0,1) or <= 1 (if it can't be negative) condition.
What is a? The alias for another table you didn't include here?
The simpler way to do this is create a storedprocedure which will take the input "#a.Id_Oem_Irm"
Example:
CREATE PROCEDURE p_get_a_data(
IN Id INT(1)
)
BEGIN
IF (Id = 0) BEGIN
--YOur query to retrieve partiular row/ column
END;
IF(Id = 1) BEGIN
--YOur query to retrieve all data
SELECT * FROM table1
where (some conditions)
END;
END
The usage of stored procedure will give you selected data and the query is precompiled in the database so it faster.
Note: I didn't quite understand what your query is returning so replace mine with yours

Execute a stored procedure within a case statement

I have an Insert Into Select statement with a Case When clause. I want to execute a stored procedure within the When statement.
Insert into Orders(id, custId, custIntake)
Select id, custId custIntake =
Case
When ( Exec mySProc(custId) = 1 ) = 'InStore'
When ( Exec mySProc(custId) = 0 ) = 'OutsideStore'
Else null
End
From OrdersImport
How can I run Exec mySProc(custId) within the Case When?
I would suggest you convert your 'mySProc' procedure into a Scalar User Defined Function if you want to run it like this. Stored Procedures are not able to do what you want.
If I understand correctly then what you need is code to run when the WHEN statement is true.
Just use CASE > WHEN > THEN as described here: http://msdn.microsoft.com/en-us/library/ms181765.aspx
Hope this helps.
Do like this.
If you set auto increment for id column, not need to mention in the query. If you need, you can add it.
Insert into orders(custId, custIntake)
Select custId, (CASE WHEN custId = '1' THEN 'InsideStore' ELSE 'OutsideStore' END) from ordersimport;
Hope, it will help you.