IF-ELSE SQL Statement - sql

I'm having a problem executing this SQL statement. I am new to TSQL and I have no idea how to fix this. Everytime I execute this, I get the error:
An expression of non-boolean type specified in a context where a
condition is expected, near ')'.
Incorrect syntax near the keyword 'else'.
if
SELECT Num from users where SUBSTRING(CAST(Num AS VARCHAR(6)),1,2) = 14
print 'Batch 2014';
else
print 'Batch 2013';
What I'm trying to do here is to search in my table all users with '13' as the first 2 numbers in the column 'Num', and then print 'Batch 2014' else 'Batch 2013' Please help :) thank you

It's best to avoid using if-else with exists. Why?
You need to make sure at least one record exists in your table
The other benefit of EXISTS is that once it finds a single record that matches it stops processing. This doesn't have a huge impact if you're checking on a primary key. It does have a big impact if you're checking for existence based on another field
if exists (SELECT Num from users where SUBSTRING(CAST(Num AS VARCHAR(6)), 1, 2) = 14)
print 'Batch 2014';
else
print 'Batch 2013';`

Your if condition returns non-boolean value (other that 0 or 1),that's the reason for getting the error.
If you are using if .. exists it will print if any of the num in your table satisfies the condition SUBSTRING(CAST(Num AS VARCHAR(6)),1,2) = 14.
If you wanted to see the users with batch information ,use CASE statement.
SELECT userid,Name -- mention the columns you wanted to select
,CASE WHEN SUBSTRING(CAST(Num AS VARCHAR(6)),1,2) =14 THEN 'Batch 2014'
ELSE 'Batch 2013' END Batch
FROM users

What the type of Num?
syntax of IF-ELSE:
-- Syntax for SQL Server, Azure SQL Database, Azure SQL Data Warehouse, Parallel Data Warehouse
IF Boolean_expression
{ sql_statement | statement_block }
[ ELSE
{ sql_statement | statement_block } ]
So, "SELECT Num from users where SUBSTRING(CAST(Num AS VARCHAR(6)),1,2) = 14" should return a Boolean, True or False.
IF EXISTS (SELECT Num from users where SUBSTRING(CAST(Num AS VARCHAR(6)),1,2) = 14)

IF EXISTS ( SELECT Num
FROM users
WHERE SUBSTRING(CAST(Num AS VARCHAR(6)), 1, 2) = 14 )
PRINT 'Batch 2014' ;
ELSE
PRINT 'Batch 2013' ;

Related

GETTING ERROR-- ORA-00936:MISSING EXPRESSION for below query please help on this

SELECT CASE (SELECT Count(1)
FROM wf_item_activity_statuses_v t
WHERE t.activity_label IN ('WAITING_DISB_REQ',
'LOG_DDE',
'LOG_SENDBACK_DDE')
AND t.item_key IN(
SELECT r.i_item_key
FROM wf_t_item_xref r
WHERE r.sz_appl_uniqueid = '20400000988')
)
WHEN 0 THEN
(
delete
from t_col_val_document_uploaded p
WHERE p.sz_application_no = '20400000988'
AND p.sz_collateral_id = 'PROP000000000PRO1701'
AND p.i_item_key = '648197'
AND p.i_document_srno = '27' )
WHEN 1 THEN
(
DELETE
FROM t_col_val_document_uploaded p
WHERE p.sz_application_no = '20400000988'
AND p.sz_collateral_id = 'PROP000000000PRO1701'
AND p.i_document_srno = '28' )
ELSE NULL
END
FROM dual;
You need to recreate your query and make sure to follow the flow of the clauses properly, please check the next two links to get a better understanding :
[ORA-00936: missing expression tips]
How do I address this ORA-00936 error?
Answer: The Oracle oerr utility notes this about the ORA-00936 error:
ORA-00936 missing expression
Cause: A required part of a clause or expression has been omitted. For example, a SELECT statement may have been entered without a list of columns or expressions or with an incomplete expression. This message is also issued in cases where a reserved word is misused, as in SELECT TABLE.
Action: Check the statement syntax and specify the missing component.
The ORA-00936 happens most frequently:
1 - When you forget list of the column names in your SELECT statement.
2. When you omit the FROM clause of the SQL statement.
ora-00936-missing-expression
I hope this can help you.
You cannot use a simple select query like this. You have to use a PL/SQL block like below -
DECLARE NUM_CNT NUMBER := 0;
BEGIN
SELECT Count(1)
INTO NUM_CNT
FROM wf_item_activity_statuses_v t
WHERE t.activity_label IN ('WAITING_DISB_REQ',
'LOG_DDE',
'LOG_SENDBACK_DDE')
AND t.item_key IN(SELECT r.i_item_key
FROM wf_t_item_xref r
WHERE r.sz_appl_uniqueid = '20400000988');
IF NUM_CNT = 0 THEN
delete
from t_col_val_document_uploaded p
WHERE p.sz_application_no = '20400000988'
AND p.sz_collateral_id = 'PROP000000000PRO1701'
AND p.i_item_key = '648197'
AND p.i_document_srno = '27';
ELSIF NUM_CNT = 1 THEN
DELETE
FROM t_col_val_document_uploaded p
WHERE p.sz_application_no = '20400000988'
AND p.sz_collateral_id = 'PROP000000000PRO1701'
AND p.i_document_srno = '28' )
END IF;
END;

How to run procedure without parameter in Teradata

How to run procedure without parameter in Teradata
I'm trying with : call db1.proc_dbOSA()
Error Msg:
Call failed 3707: PROC_DBOSA: Syntax error, expected something
like a name or a Unicode delimited identifier between ‘(‘ and ‘)’
New Procedure with error result.
When i run only code then everything works ok.
REPLACE PROCEDURE db1.proc_dbOSA()
BEGIN
DELETE FROM db1.LOG_dbOSA;
INSERT INTO
db1.LOG_dbOSA
(StoreNo, IDX, Flow, Status, MRP, OSA_IDX, OSA_AC)
WITH a AS (
SELECT
c.StoreCode,
CAST(SUBSTRING(c.ArticleCode FROM 13 FOR 6) AS INT) AS IDX,
RpType,
CASE
WHEN c.MinimumTargetStockWrpl >= l.MinimumTargetStockWrpl THEN CAST(l.MinimumTargetStockWrpl AS INT)
WHEN c.MinimumTargetStockWrpl < l.MinimumTargetStockWrpl THEN CAST(c.MinimumTargetStockWrpl AS INT)
End AS StoreMin,
c.ValUnrestrictedStock
FROM
db1.tab1 c
INNER JOIN
(
SELECT
StoreCode,
ArticleCode,
MinimumTargetStockWrpl
FROM
db1.tab1
WHERE
ProcessingDate = CURRENT_DATE - 14
) l ON c.StoreCode = l.StoreCode AND c.ArticleCode = l.ArticleCode
WHERE
c.ProcessingDate = CURRENT_DATE AND c.MinimumTargetStockWrpl IS NOT NULL AND l.MinimumTargetStockWrpl IS NOT NULL AND l.MinimumTargetStockWrpl > 0
)
, t AS
(
SELECT
CAST(SUBSTRING(ArticleCode FROM 13 FOR 6) AS INT) AS IDX,
RpType,
ArticlesPlanner
FROM
DWH_db_V.STK_B_ARTICLE_DAY_V
WHERE
ProcessingDate = CURRENT_DATE AND StoreCode = 'DR04'
)
SELECT
a.StoreCode,
a.IDX,
t.RpType,
t.ArticlesPlanner,
a.RpType,
CASE
WHEN a.ValUnrestrictedStock > 0 THEN 1
WHEN a.ValUnrestrictedStock <= 0 THEN 0
End AS OSA_IDX,
CASE
WHEN a.ValUnrestrictedStock >= StoreMin THEN 1
WHEN a.ValUnrestrictedStock < StoreMin THEN 0
End AS OSA_AC
FROM
a
LEFT JOIN
t ON t.IDX = a.IDX;
End;
BTEQ Error:
+---------+---------+---------+---------+---------+---------+---------+----
Call proc_dbOSA;
Call proc_dbOSA;
$
* Failure 3707 Syntax error, expected something like '(' between the word
'proc_dbOSA' and ';'.
Statement# 1, Info =18
* Total elapsed time was 1 second.
Call proc_dbOSA();
* Failure 3707 PROC_DBOSA:Syntax error, expected something like a name or
a Unicode delimited identifier between '(' and ')'.
* Total elapsed time was 1 second.
Stored procedures do not support the following:
EXPLAIN and USING request modifiers within a stored procedure
EXECUTE macro statement
WITH clause within a stored procedure.
Stored procedures, as well as macros, do not support the following query logging statements:
BEGIN QUERY LOGGING
END QUERY LOGGING
FLUSH QUERY LOGGING
REPLACE QUERY LOGGING

Incorrect syntax near 'End' , not letting run the query nor create procedure

Not letting me create the procedure, nor not letting run this query please help.
It's not letting run the query .. this is just a section of query
You had a few things wrong, you didnt need the parens, you were missing an End Statement, and your indents made it hard to read, and you are missing your FROM statement, so I put FROM and added tableName you need to fill this in.
create proc [dbo].[a_test]
as
begin
SELECT top 10
file_ty = '5',
cno= rtrim(ltrim(adm.AccountNumber)),
Column3='',
Column4='',
Admit_Date =
CASE
WHEN RegistrationType_MisRegTypeID <>'IN'
THEN ''
ELSE CONVERT(varchar(10),replace(convert(varchar(10),adm.AdmitDateTime,101),'/ ',''))
END,
Point_Of_Origin =
CASE
WHEN RegistrationType_MisRegTypeID='IN' then
CASE
WHEN AdmitSource='CIR' then '2'
WHEN AdmitSource='BSH' then '2'
ELSE ''
END
END
FROM dbo.TableName
END

SAP HANA SQL Query with Dynamic Placeholder

I have a query that is passing the current year as a placeholder parameter that right now is hard coded. How can I have this just pass the current year? I've seen a few different potential solutions but most of them are in HANA Studio or involve dynamic SQL generation.
I'm putting the SQL into Tableau so those are both off the table.
...sum("StockInQualityInspection") as in_quality,
sum("StockInTransit") as its
from "_SYS_BIC"."stream.models.marketing.poly/InventoryQuery" ('PLACEHOLDER' = ('$$IPCurrentYear$$', '2018'))
where "StockValuatedUnrestrictedUse" <> 0 or "StockInQualityInspection" <> 0 or "StockInTransit" <> 0
group by case when "ReceivingPlant" is null then "Plant" else "ReceivingPlant" end,
case....
Remove the parameters input of your CV
Add this expression: year(now())
If you don't have access to manipulate the CV, into your query use:
('PLACEHOLDER' = ('$$IPCurrentYear$$', select year(now()) from DUMMY))
Regards
while placing a query is not permitted, you can pass a parameter as following
do begin
declare lv_param nvarchar(100);
select max('some_date')
into lv_param
from dummy /*your_table*/;
select *
from "_SYS_BIC"."path.to.your.view/CV_TEST" (
PLACEHOLDER."$$P_DUMMY$$" => :lv_param
);
end;
more can be found here
credit to #astentx

MSSQL Stored Procedure with dynamically added WHERE?

I have this Stored Procedure, where i need to check if #DateChk == 1, THEN i want to add a WHERE-clause to the SQL statement in the SP. If its 0, there should not be any WHERE-clause.
How do i script such function? In a program i could just build in the string to pass to the server, but i have not found any way to do this in the SQL server.
SELECT dateDay, SUM(nok) as NOK, SUM(ok) as OK, (SUM(ok) + SUM(nok)) as 'Total'
FROM #st
SELECT CASE #DateChk
WHEN 1: WHERE dateDay BETWEEN '2016-08-01' AND '2016-08-31'
Something like this, if #DateChk = 1, the WHERE should be added, else fetch all records.
You can modify your condition like this:
SELECT dateDay, SUM(nok) as NOK, SUM(ok) as OK, (SUM(ok) + SUM(nok)) as 'Total'
FROM #st
WHERE
(#DateChk = 1 and (dateDay BETWEEN '2016-08-01' AND '2016-08-31'))
or #DateChk = 0
And it will exactly match your desired behaviour: condition on dateDay will be applied only when #DateChk = 1.