How can use the result of case statements in to another manipulation? - sql-server-2008

select 'Test '+m.testname+' '+
Case
When m.value = 'ttttt' Then 'tt'
When m.styleName = 'ppppp' Then 'pp'
When m.styleName = 'qqqqq' Then 'qq'
When m.styleName = 'yyyyyy' Then 'yy'
Else ''
End from testtable m where m.id=10'
This is my query, i need to check the length of string formed after case statement.if the length greater than 35 then i want to remove charecters from "m.testname" field.
Thanks for your help.

You can use your current query as a derived table:
select YourString,
LEN(YourString) [Length],
Case
When LEN(YourString) > 35 THEN REPLACE(YourString,testname,'')
Else YourString
End YourNewString
from ( select 'Test '+m.testname+' '+
Case
When m.value = 'ttttt' Then 'tt'
When m.styleName = 'ppppp' Then 'pp'
When m.styleName = 'qqqqq' Then 'qq'
When m.styleName = 'yyyyyy' Then 'yy'
Else ''
End YourString,
m.testname
from testtable m
where m.id=10) a
;
Or you can use a CTE:
WITH CTE AS
(
select 'Test '+m.testname+' '+
Case
When m.value = 'ttttt' Then 'tt'
When m.styleName = 'ppppp' Then 'pp'
When m.styleName = 'qqqqq' Then 'qq'
When m.styleName = 'yyyyyy' Then 'yy'
Else ''
End YourString,
m.testname
from testtable m
where m.id=10
)
select YourString,
LEN(YourString) [Length],
Case
When LEN(YourString) > 35 THEN REPLACE(YourString,testname,'')
Else YourString
End YourNewString
from CTE;

Related

order by not working in stored procedure mysql

select
tr.TransactionId as TxnIdentifier,
m.MerchantName as MerchantName,
case
when tr.ChannelType=2 then 'ACH'
when tr.ChannelType=3 then 'CC'
when tr.ChannelType=4 then 'Debit'
else null
end as ChannelType,
tr.CaptureAmount as CaptureAmount,
case when tr.OperationType=0 then 'Sale'
when tr.OperationType=1 then 'Verify only'
when tr.OperationType=2 then 'ForceSale'
when tr.OperationType=3 then 'Adjust'
when tr.OperationType=4 then 'Activate'
when tr.OperationType=5 then 'Deactivate'
when tr.OperationType=6 then 'Reload'
when tr.OperationType=7 then 'Refund'
when tr.OperationType=8 then 'Inquire'
else null end as TxnType,
case when tr.TransactionStatus=0 then 'Created'
when tr.TransactionStatus=1 then 'Pending'
when tr.TransactionStatus=2 then 'Authorized'
when tr.TransactionStatus=3 then 'Posted'
when tr.TransactionStatus=4 then 'Accepted'
when tr.TransactionStatus=5 then 'Failed'
when tr.TransactionStatus=6 then 'Returned'
when tr.TransactionStatus=7 then 'Chargeback'
when tr.TransactionStatus=8 then 'Void'
when tr.TransactionStatus=9 then 'Refunded'
when tr.TransactionStatus=10 then 'Approved'
when tr.TransactionStatus=11 then 'Void attempted'
when tr.TransactionStatus=12 then 'Refund attempted'
when tr.TransactionStatus=13 then 'Hold'
when tr.TransactionStatus=14 then 'Denied'
when tr.TransactionStatus=15 then 'Settlement hold'
when tr.TransactionStatus=16 then 'Success'
when tr.TransactionStatus=17 then 'Retried'
when tr.TransactionStatus=100 then 'Unknown'
else null end as TxnStatus,
tr.PreAuthCode as AuthCode,
DATE_FORMAT(tr.TransactionDate, '%m-%d-%Y %H:%i:%s') as TransactionDate,
case when tr.OperationType='7' then tr.Amount
else null end as RefundAmount,
case when tr.OperationType='7'
then DATE_FORMAT(tr.TransactionDate, '%m-%d-%Y %H:%i:%s')
else null end as RefundedOn,
tr.TraceNumber as TraceNumber
from TransactionEntity tr
inner join `enter code here`DOMAIN.Merchant m on m.Id=tr.MerchantId where 1=1
and (tr.MerchantId = merchantId or merchantId=0)
and (tr.ChannelType = channelType or channelType=0)
And (tr.TransactionDate >= startDate or startDate is null)
And (tr.TransactionDate <= endDate or endDate is null)
ORDER BY
CASE WHEN sortField = 'TransactionDate' AND sortDirection='ASC' THEN TransactionDate END ASC,
CASE WHEN sortField = 'TransactionDate' AND sortDirection='DESC' THEN TransactionDate END DESC
If I apply order by clause outside the stored procedure it works fine but inside the sp it didn't work (applying order by desc on TransactionDate not working)
Try creating your stored procedure like below then
DELIMITER //
CREATE PROCEDURE select_whatever(sortField VARCHAR(20), sortDirection CHAR(4))
BEGIN
DECLARE select_clause TEXT;
DECLARE order_by_clause VARCHAR(100);
SET select_clause = "
select
tr.TransactionId as TxnIdentifier,
m.MerchantName as MerchantName,
case
when tr.ChannelType=2 then 'ACH'
when tr.ChannelType=3 then 'CC'
when tr.ChannelType=4 then 'Debit'
else null
end as ChannelType,
tr.CaptureAmount as CaptureAmount,
case
when tr.OperationType=0 then 'Sale'
when tr.OperationType=1 then 'Verify only'
when tr.OperationType=2 then 'ForceSale'
when tr.OperationType=3 then 'Adjust'
when tr.OperationType=4 then 'Activate'
when tr.OperationType=5 then 'Deactivate'
when tr.OperationType=6 then 'Reload'
when tr.OperationType=7 then 'Refund'
when tr.OperationType=8 then 'Inquire'
else null
end as TxnType,
case
when tr.TransactionStatus=0 then 'Created'
when tr.TransactionStatus=1 then 'Pending'
when tr.TransactionStatus=2 then 'Authorized'
when tr.TransactionStatus=3 then 'Posted'
when tr.TransactionStatus=4 then 'Accepted'
when tr.TransactionStatus=5 then 'Failed'
when tr.TransactionStatus=6 then 'Returned'
when tr.TransactionStatus=7 then 'Chargeback'
when tr.TransactionStatus=8 then 'Void'
when tr.TransactionStatus=9 then 'Refunded'
when tr.TransactionStatus=10 then 'Approved'
when tr.TransactionStatus=11 then 'Void attempted'
when tr.TransactionStatus=12 then 'Refund attempted'
when tr.TransactionStatus=13 then 'Hold'
when tr.TransactionStatus=14 then 'Denied'
when tr.TransactionStatus=15 then 'Settlement hold'
when tr.TransactionStatus=16 then 'Success'
when tr.TransactionStatus=17 then 'Retried'
when tr.TransactionStatus=100 then 'Unknown'
else null
end as TxnStatus,
tr.PreAuthCode as AuthCode,
DATE_FORMAT(tr.TransactionDate, '%m-%d-%Y %H:%i:%s') as TransactionDate,
case
when tr.OperationType='7' then tr.Amount
else null
end as RefundAmount,
case
when tr.OperationType='7'
then DATE_FORMAT(tr.TransactionDate, '%m-%d-%Y %H:%i:%s')
else null
end as RefundedOn,
tr.TraceNumber as TraceNumber
from TransactionEntity tr
inner join `enter code here`DOMAIN.Merchant m on m.Id=tr.MerchantId where 1=1
and (tr.MerchantId = merchantId or merchantId=0)
and (tr.ChannelType = channelType or channelType=0)
And (tr.TransactionDate >= startDate or startDate is null)
And (tr.TransactionDate <= endDate or endDate is null)
";
SET order_by_clause = "ORDER BY";
IF sortField = "TransactionDate" AND sortDirection="ASC" THEN
SET order_by_clause = CONCAT(order_by_clause, " TransactionDate ASC")
ELSEIF sortField = "TransactionDate" AND sortDirection="DESC" THEN
SET order_by_clause = CONCAT(order_by_clause, " TransactionDate DESC")
END IF
SET #dynamic_sql = CONCAT(select_clause, ' ', order_by_clause);
PREPARE select_whatever_statement
FROM #dynamic_sql;
EXECUTE select_whatever_statement;
DEALLOCATE PREPARE select_whatever_statement;
END //
DELIMITER ;

sql two order by give different result

I have this sql query below that has 2 order by my dates are
02/01/2016 - 03/01/2017
02/03/2011 - 07/07/2016
12/22/2010 - 07/07/2016
02/01/2016 - 02/01/2016
12/22/2010 - 07/07/2013
This is the result when i use the query below. But the problem is it is not in order in what i expect for. I want to order first the DateEnd in desc order and then the DateStarted.
Select top 5
Case When dbo.VoluntaryWork.Organization + ' - ' + dbo.VoluntaryWork.OrganizationAddress = ' - '
Then 'N/A'
Else dbo.VoluntaryWork.Organization + ' - ' + dbo.VoluntaryWork.OrganizationAddress end AS OrgAddress,
Case When isnull(CONVERT(varchar(10), dbo.VoluntaryWork.DateStarted, 101),'') = '' or isnull(CONVERT(varchar(10), dbo.VoluntaryWork.DateStarted, 101),'') = '01/01/1900' then 'N/A' else isnull(CONVERT(varchar(10), dbo.VoluntaryWork.DateStarted, 101),'') end AS DateStarted,
Case When isnull(CONVERT(varchar(10), dbo.VoluntaryWork.DateEnded, 101),'') = '' or isnull(CONVERT(varchar(10), dbo.VoluntaryWork.DateEnded, 101),'') = '01/01/1900' then 'N/A' else isnull(CONVERT(varchar(10), dbo.VoluntaryWork.DateEnded, 101),'') end AS DateEnded
From dbo.PersonVoluntaryWork
Inner Join dbo.VoluntaryWork ON dbo.PersonVoluntaryWork.VoluntaryWorksId = dbo.VoluntaryWork.VoluntaryWorksId
Where (dbo.PersonVoluntaryWork.PersonId = #PersonId)
Order By dbo.VoluntaryWork.DateEnded desc ,dbo.VoluntaryWork.DateStarted desc
Hi use another select clause from outside your main query and then apply order by clause like this.. I hope this will work.
SELECT * from (
SELECT top 5 case when dbo.VoluntaryWork.Organization + ' - ' + dbo.VoluntaryWork.OrganizationAddress = ' - ' then 'N/A'
else dbo.VoluntaryWork.Organization + ' - ' + dbo.VoluntaryWork.OrganizationAddress end AS OrgAddress,
case when isnull(CONVERT(varchar(10), dbo.VoluntaryWork.DateStarted, 101),'') = '' or isnull(CONVERT(varchar(10), dbo.VoluntaryWork.DateStarted, 101),'') = '01/01/1900' then 'N/A' else isnull(CONVERT(varchar(10), dbo.VoluntaryWork.DateStarted, 101),'') end AS DateStarted,
case when isnull(CONVERT(varchar(10), dbo.VoluntaryWork.DateEnded, 101),'') = '' or isnull(CONVERT(varchar(10), dbo.VoluntaryWork.DateEnded, 101),'') = '01/01/1900' then 'N/A' else isnull(CONVERT(varchar(10), dbo.VoluntaryWork.DateEnded, 101),'') end AS DateEnded,
FROM dbo.PersonVoluntaryWork INNER JOIN
dbo.VoluntaryWork ON dbo.PersonVoluntaryWork.VoluntaryWorksId = dbo.VoluntaryWork.VoluntaryWorksId
WHERE (dbo.PersonVoluntaryWork.PersonId = #PersonId)
ORDER BY dbo.VoluntaryWork.DateEnded DESC
) A ORDER BY A.DateStarted

Error in last line near end

While i Execute a stored procedure I don't know why showing error in last line...
I can't find any error with it
The error is telling
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near '' at
line 60
_
CREATE PROCEDURE `PartyBalanceViewByLedgerId`
(
p_ledgerId varchar(50),
p_crOrDr varchar(50),
p_branchId varchar(50)
)
BEGIN
IF (p_crOrDr='Dr')
THEN
SELECT
TEMP.voucherNo +'_'+ TEMP.voucherType AS ID,
TEMP.voucherType,
CASE WHEN (TEMP.voucherType = 'Receipt Voucher')
THEN
(SELECT receiptMasterId FROM tbl_ReceiptMaster
WHERE (receiptMasterId = TEMP.voucherNo))
ELSE
(SELECT purchaseMasterId FROM tbl_PurchaseMaster
WHERE (purchaseMasterId = TEMP.voucherNo))
END AS voucherNo,
CAST(CAST(TEMP.balance AS DECIMAL(24,2)) AS char(27))
AS amount
FROM(SELECT
A.voucherNo,
A.voucherType,
(SUM(ifnull(A.credit, 0)) - SUM(ifnull(A.debit, 0)))
AS balance
FROM tbl_PartyBalance AS A
WHERE (A.voucherType = 'Purchase Invoice'
OR A.voucherType = 'Receipt Voucher')
AND A.ledgerId=p_ledgerId
AND A.branchId=p_branchId
AND A.optional='False'
GROUP BY A.voucherNo,A.voucherType
)AS TEMP
WHERE TEMP.Balance>0 ;
ELSE
SELECT
TEMP.voucherNo +'_'+ TEMP.voucherType ID,
TEMP.voucherType,
CASE WHEN TEMP.voucherType = 'Payment Voucher' THEN
(SELECT paymentMasterId FROM tbl_PaymentMaster WHERE (paymentMasterId = TEMP.voucherNo))
ELSE
(SELECT salesInvoiceNo FROM tbl_SalesMaster WHERE (salesMasterId = TEMP.voucherNo)) END AS voucherNo,
CAST(CAST(TEMP.balance AS DECIMAL(24,2))AS char(27)) AS amount
FROM(
SELECT
A.voucherNo,
A.voucherType,
(SUM(ifnull(A.debit, 0)) - SUM(ifnull(A.credit,0))) AS balance
FROM tbl_PartyBalance AS A
WHERE (A.voucherType = 'Sales Invoice' OR A.voucherType = 'Payment Voucher'OR A.voucherType = 'Job Invoice') AND A.ledgerId=p_ledgerId AND A.branchId=p_branchId AND A.optional='False'
GROUP BY A.voucherNo,A.voucherType
)AS TEMP
WHERE TEMP.Balance > 0 ;
END
try with this i have update some changes END IF and ; etc
CREATE PROCEDURE `PartyBalanceViewByLedgerId`
(
p_ledgerId varchar(50),
p_crOrDr varchar(50),
p_branchId varchar(50)
)
BEGIN
IF (p_crOrDr='Dr')
SELECT
TEMP.voucherNo +'_'+ TEMP.voucherType AS ID,
TEMP.voucherType,
CASE WHEN (TEMP.voucherType = 'Receipt Voucher')
THEN
(SELECT receiptMasterId FROM tbl_ReceiptMaster
WHERE (receiptMasterId = TEMP.voucherNo))
ELSE
(SELECT purchaseMasterId FROM tbl_PurchaseMaster
WHERE (purchaseMasterId = TEMP.voucherNo))
END AS voucherNo,
CAST(CAST(TEMP.balance AS DECIMAL(24,2)) AS char(27))
AS amount
FROM(SELECT
A.voucherNo,
A.voucherType,
(SUM(ifnull(A.credit, 0)) - SUM(ifnull(A.debit, 0)))
AS balance
FROM tbl_PartyBalance AS A
WHERE (A.voucherType = 'Purchase Invoice'
OR A.voucherType = 'Receipt Voucher')
AND A.ledgerId=p_ledgerId
AND A.branchId=p_branchId
AND A.optional='False'
GROUP BY A.voucherNo,A.voucherType
)AS TEMP
WHERE TEMP.Balance>0;
ELSE
SELECT
TEMP.voucherNo +'_'+ TEMP.voucherType ID,
TEMP.voucherType,
CASE WHEN TEMP.voucherType = 'Payment Voucher' THEN
(SELECT paymentMasterId FROM tbl_PaymentMaster WHERE (paymentMasterId = TEMP.voucherNo))
ELSE
(SELECT salesInvoiceNo FROM tbl_SalesMaster WHERE (salesMasterId = TEMP.voucherNo)) END AS voucherNo,
CAST(CAST(TEMP.balance AS DECIMAL(24,2))AS char(27)) AS amount
FROM(
SELECT
A.voucherNo,
A.voucherType,
(SUM(ifnull(A.debit, 0)) - SUM(ifnull(A.credit,0))) AS balance
FROM tbl_PartyBalance AS A
WHERE (A.voucherType = 'Sales Invoice' OR A.voucherType = 'Payment Voucher'OR A.voucherType = 'Job Invoice') AND A.ledgerId=p_ledgerId AND A.branchId=p_branchId AND A.optional='False'
GROUP BY A.voucherNo,A.voucherType
)AS TEMP
WHERE TEMP.Balance > 0 ;
END IF;
END;
Are you using a DELIMITER? If not pl go through this description:
Delimiters in MySQL
I hope this will solve your problem.
Remove the semicolon before ELSE in :
GROUP BY A.voucherNo,A.voucherType
)AS TEMP
WHERE TEMP.Balance>0
ELSE
SELECT
TEMP.voucherNo +'_'+ TEMP.voucherType ID,
TEMP.voucherType,

If statement to distinguish which "Case" query should be added to select query

I'm stacked on following query. I need to create an if statement or something similar to distinguish which "CASE" should be added to my select query.
If page_type = 'Region' or 'City' add this to the query:
( CASE When landing_page like concat('%',path_id,'%') and
(LENGTH(landing_page) - LENGTH(REPLACE(landing_page, '/' ,'')) / LENGTH('/')) = 2
Then 'True' Else 'False' End as 'correct lp' , )
Elseif page_type = 'Item' add this to the query:
( CASE When landing_page like concat('%',path_id,'%') and
(LENGTH(landing_page) - LENGTH(REPLACE(landing_page, '/' ,'')) / LENGTH('/')) = 3
Then 'True' Else 'False' End as 'correct lp' , )
Elseif page_type = 'POI (Alle)' add this to the query:
( CASE When landing_page like concat('%',path_id,'%') and
(LENGTH(landing_page) - LENGTH(REPLACE(landing_page, '/' ,'')) / LENGTH('/')) = 3 and
'Hotel' NOT IN landing_page
Then 'True' Else 'False' End as 'correct lp' , )
Case queries should be added to the following query according to if outcome:
SELECT
MONTHNAME(k.crawl_date) As 'Month',
YEAR(k.crawl_date) As 'Year',
WEEKOFYEAR(k.crawl_date) As 'Week',
k.landing_page,
k.pos,
CASE WHEN k.pos = 0 THEN 'No Rank' WHEN k.pos < 4 THEN 'Top 3' WHEN k.pos < 11 THEN 'Page 1'
WHEN k.pos < 21 THEN 'Page 2' WHEN k.pos < 31 THEN 'Page 3' WHEN k.pos < 41 THEN 'Page 4'
WHEN k.pos < 51 THEN 'Page 5' WHEN k.pos < 61 THEN 'Page 6' WHEN k.pos < 71 THEN 'Page 7'
WHEN k.pos < 81 THEN 'Page 8' WHEN k.pos < 91 THEN 'Page 9' WHEN k.pos < 101 THEN 'Page 10'
WHEN k.pos < 111 THEN 'Page 11' END as 'Page',
k.path_id,
k.domain,
x.keyword,
x.engine_id,
l.bucket,
l.page_type,
l.item_label
FROM
xovi_stats k
LEFT JOIN xovi_keywords x ON k.keyword_id = x.id
LEFT JOIN xovi_labels l ON l.id = x.label_id
You can nest CASE clauses like this:
SELECT
CASE
WHEN (page_type IN ('Region', 'City')) THEN
CASE
WHEN landing_page LIKE ... THEN 'True'
ELSE 'False'
END
WHEN (page_type = 'Item') THEN
CASE
...
END
WHEN (page_type = 'POI (Alle)') THEN
CASE
...
END
END AS lp,
MONTHNAME(k.crawl_date) As 'Month', -- other fields
...
Or you can also nest IF(), as you suggest:
SELECT
IF ( (page_type IN ('Region', 'City')),
-- if (page_type IN ('Region', 'City')) then
CASE
WHEN landing_page LIKE ... THEN 'True'
ELSE 'False'
END,
-- else
IF ( (page_type = 'Item'),
-- if (page_type = 'Item') then
CASE
...
END,
-- else
IF ( page_type = 'POI (Alle)',
-- if (page_type = 'POI (Alle)') then
CASE
...
END,
-- else
NULL
)
)
) AS lp,
MONTHNAME(k.crawl_date) As 'Month', -- other fields
...
Off-topic notes:
you can replace your two-branch CASE statements with simple IF():
SELECT CASE
WHEN landing_page LIKE ... THEN 'True'
ELSE 'False'
END AS alias ;
-- strictly equivalent to
SELECT IF(
landing_page LIKE ...,
'True',
'False'
) AS alias ;
you can replace your large existing CASE with:
CASE
WHEN k.pos = 0 THEN 'No Rank'
WHEN k.pos < 4 THEN 'Top 3'
ELSE CONCAT('Page ', (k.pos -1) DIV 10 +1 )
END AS 'Page'

SQL Conditional Statement in Where Clause

I would like to write the following IF statement in SQL. Most of the where clause is constructed, but it's the condition around the statement that I'm struggling with:
if #StuYear = 11 then
AND (#TeachingGroup = 'Select All')
AND ([DataCollection] = #DataCollection)
AND ([Name] = #SubjectName)
AND (#Subgroup='Select All')
AND '' = CASE #subjectName WHEN 'English' THEN KS2en WHEN 'Mathematics' THEN KS2ma ELSE KS2av END
AND Result Not Like '[ABU]%' AND Result <> ''
else if #StuYear = 10 then
AND #TeachingGroup Not Like 'Select All'
AND ([DataCollection] = #DataCollection)
AND ([Name] = #SubjectName)
AND ([TeachingGroup] = #TeachingGroup)
AND #Subgroup='Select All'
AND '' = CASE #subjectName WHEN 'English' THEN KS2en WHEN 'Mathematics' THEN KS2ma ELSE KS2av END
AND Result Not Like '[ABC]%' AND Result <> ''
end if
Simply replace if with where and else if with or and surround the other conditions in paranthesis:
...
where (#StuYear = 11
AND (#TeachingGroup = 'Select All')
AND ([DataCollection] = #DataCollection)
AND ([Name] = #SubjectName)
AND (#Subgroup='Select All')
AND '' = CASE #subjectName WHEN 'English' THEN KS2en WHEN 'Mathematics' THEN KS2ma ELSE KS2av END
AND Result Not Like 'A*'
AND Result Not Like 'A'
AND Result Not Like 'B'
AND Result Not Like 'U'
AND Result Not Like '' )
OR (#StuYear = 10
AND #TeachingGroup Not Like 'Select All'
AND ([DataCollection] = #DataCollection)
AND ([Name] = #SubjectName)
AND ([TeachingGroup] = #TeachingGroup)
AND #Subgroup='Select All'
AND '' = CASE #subjectName WHEN 'English' THEN KS2en WHEN 'Mathematics' THEN KS2ma ELSE KS2av END
AND Result Not Like 'A*'
AND Result Not Like 'A'
AND Result Not Like 'B'
AND Result Not Like 'C'
AND Result Not Like '')
Tim's answer helped point me in the right direction. However, I eventually resolved the issue by applying the year condition within the where clause as opposed to rapping it around them:
where
(#StuYear = [stuyear]
AND #TeachingGroup = 'Select All'
AND [DataCollection] = #DataCollection
AND [Name] = #SubjectName
AND #Subgroup='Select All'
AND '' = CASE #subjectName WHEN 'English' THEN KS2en WHEN 'Mathematics' THEN KS2ma ELSE KS2av END
AND ((Result Not Like '[ABU]%' and result not like '' and stuyear='11')
or(Result Not Like '[ABC]%' and result not like '' and stuyear='10')
or(Result Not Like '[ABCD]%' and stuyear='9'))
AND Result <> '')
OR
(#StuYear = [stuyear]
AND #TeachingGroup Not Like 'Select All'
AND [DataCollection] = #DataCollection
AND [Name] = #SubjectName
AND [TeachingGroup] = #TeachingGroup
AND #Subgroup='Select All'
AND '' = CASE #subjectName WHEN 'English' THEN KS2en WHEN 'Mathematics' THEN KS2ma ELSE KS2av END
AND ((Result Not Like '[ABU]%' and result not like '' and stuyear='11')
or(Result Not Like '[ABC]%' and result not like '' and stuyear='10')
or(Result Not Like '[ABCD]%' and stuyear='9'))
AND Result <> '')