Why would this "Fail", if foo is less than 40 it should be "OK"
SELECT foo = '30', case when 'foo' >= '40' then 'Fail' else 'OK' end as 'Test'
So my actual query is (where ArrivalDate is a datetime):
SELECT Distinct [Title]
,DATEDIFF(day, [ArrivalDate], GetDate()) AS 'DaysOldSinceArrival'
,case when 'DaysOldSinceArrival' >= '40' then 'Fail' else 'OK' end as 'Test'
I believe the 'DaysOldSinceArrival' output must be a string and this is why the compare is not working. Is this failing for the same reason, if so, how do I make the 'DaysOldSinceArrival' an actual INT?
Your query is not correct, I feel you are trying to do something like following.
DECLARE #FOO INT
SET #FOO =30
SELECT #foo , case when #foo >= 40
then 'Fail' else 'OK' end as 'Test'
Output
(No column name) Test
30 OK
Issues in your query. You are comparing string 'foo' with a string
value '40', which is not ture.
EDIT
After looking your update, it seems you want to do like following
SELECT *,
(case when DaysOldSinceArrival >= 40 then 'Fail' else 'OK' end) as 'Test'
FROM
(
SELECT Distinct [Title]
,DATEDIFF(day, [ArrivalDate], GetDate()) AS 'DaysOldSinceArrival'
FROM [YOUR_TABLE]
) T
Yes, you are comparing a string to an INT which is implictly converted to a string and thus desn't equal your other string. You could use a CTE which can be more clear than a derrived table for some.
;with cte as(
SELECT
Distinct [Title]
,DaysOldSinceArrival = DATEDIFF(day, [ArrivalDate], GetDate()))
select
*
,Test = case when DaysOldSinceArrival >= 40 then 'Fail' else 'OK' end
from cte
Related
i try to build a store procedure who insert data to a table,
after it run, the table is empty.
this is the code:
CREATE TABLE invoices
(invoiceNo int,
invoiceDate date,
invoiceTotal int,
invoiceType char(1))
alter PROCEDURE Invoices_AGG
#year int
AS
select
(case when MONTH(invoiceDate) >9 then concat('01','/',MONTH(invoiceDate),'/',year(invoiceDate)) else concat('01','/0',MONTH(invoiceDate),'/',year(invoiceDate)) end) as DateID,
SUM(case when invoiceType = 'B' then invoiceTotal else 0 end) as Total_Incomes_TypeB,
SUM(case when invoiceType = 'I' then invoiceTotal else 0 end) as Total_Incomes_TypeI
into FACT_Invoices_AGG
from invoices
where year(invoiceDate)=#year
group by (case when MONTH(invoiceDate) >9 then concat('01','/',MONTH(invoiceDate),'/',year(invoiceDate)) else concat('01','/0',MONTH(invoiceDate),'/',year(invoiceDate)) end);
exec Invoices_AGG 2013
thank you
you haven't specified the table in which you want to insert data and since your table is empty on which you are applying your select query it's returning no result.
If you want to use
into
you should also mention your code for FACT_Invoices_AGG function.
The SELECT INTO statement creates a table and fills it with data. Executing 2 or more times that statement will fail (since the table will be created on the first run and will try to create it again on the second one).
If the table is empty is either because the query returned no results, or the SP failed because of the reason I mentioned before (or even failed while building the results, for example with a bad conversion). When using SELECT INTO, make sure to drop the table IF EXISTS before (if this is what you want).
ALTER PROCEDURE Invoices_AGG
#year int
AS
BEGIN
IF EXISTS( SELECT 'table exists' FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N'FACT_Invoices_AGG'AND TABLE_SCHEMA = 'dbo')
DROP TABLE dbo.FACT_Invoices_AGG
select
(case when MONTH(invoiceDate) >9 then concat('01','/',MONTH(invoiceDate),'/',year(invoiceDate)) else concat('01','/0',MONTH(invoiceDate),'/',year(invoiceDate)) end) as DateID,
SUM(case when invoiceType = 'B' then invoiceTotal else 0 end) as Total_Incomes_TypeB,
SUM(case when invoiceType = 'I' then invoiceTotal else 0 end) as Total_Incomes_TypeI
into
FACT_Invoices_AGG
from
invoices
where
year(invoiceDate)=#year
group by
(case when MONTH(invoiceDate) >9 then concat('01','/',MONTH(invoiceDate),'/',year(invoiceDate)) else concat('01','/0',MONTH(invoiceDate),'/',year(invoiceDate)) end);
END
GO
Another option would be changing your SELECT INTO for a INSERT INTO (columnNames, ...) SELECT which requires that the table exists beforehand.
Try executing the SELECT without the INTO to see if it doesn't fail while computing the result. If it doesn't then make sure the destination table does not exist before using a SELECT INTO.
;with cte as select * from customer
the select cte order by passing parameter
if(#orderby=1)
begin
select * from cte order by name
end
else if (#oderby=2)
begin
select * from cte order by applydate
end
else
begin
select * from cte order by customeramount
end
this following error invalid object cte How to Solve this sql query
I have to Solve The Problem
The code is
SELECT * FROM cte ORDER BY CASE #OrderBy WHEN 0 THEN Name ELSE null END , CASE #OrderBy WHEN 1 THEN Code ELSE null END ,CASE #OrderBy WHEN 2 THEN ApplyAmountTotal ELSE null END ,CASE #OrderBy WHEN 3 THEN ApplyDate ELSE null END
You can use case as below:
;With cte as
( select * from customer )
Select * from cte
Order by (case when #orderby=1 then [name]
when #orderby=2 then applydate
else customerAmount end )
I am find the Answer
SELECT * FROM cte ORDER BY CASE #OrderBy WHEN 0 THEN Name ELSE null END , CASE #OrderBy WHEN 1 THEN Code ELSE null END ,CASE #OrderBy WHEN 2 THEN ApplyAmountTotal ELSE null END ,CASE #OrderBy WHEN 3 THEN ApplyDate ELSE null END
name, applydate, customerAmount are not the same data type,
then you could use 3 CASE ...END clauses like this
SELECT *
FROM customer
ORDER BY
CASE
WHEN #oderby = 1 THEN name
ELSE ''
END,
CASE
WHEN #oderby = 2 THEN applydate
ELSE '1900-01-01'
END,
CASE
WHEN #oderby NOT IN (1,2) THEN customerAmount
ELSE 1
END
I have the following query that fails to run stating "History queries must contain at least one valid tagname". This one has me stumped.
DECLARE #tag varchar(255),
#sqlstring varchar(4000)
SET #tag = 'rm01'
SELECT
value
FROM StringHistory e
INNER JOIN (SELECT
badge,
lastname AS name
FROM [LOCALSERVER].[my_log].[dbo].[local_Operators]
WHERE type = '''op''') u
ON e.value = u.badge
AND e.TagName = 'first' + (CASE
WHEN #tag = 'rm01' THEN '03'
END) + '_dat_badge'
AND DateTime >= DATEADD(HH, -12, GETDATE())
AND DateTime <= GETDATE()
I am assuming it has to do with the case statement and a single quote? because if I remove the case statement and just use ('03') the query runs.
Thank You
Your CASE-expression has no ELSE specified. This will result in a NULL being returned, which will lead to 'first' + NULL + '_dat_badge' which in turn is NULL.
I believe adding the ELSE with an empty string will solve the error.
SELECT
value
FROM StringHistory e
INNER JOIN (SELECT
badge,
lastname AS name
FROM [LOCALSERVER].[my_log].[dbo].[local_Operators]
WHERE type = '''op''') u
ON e.value = u.badge
AND e.TagName = 'first' + (CASE
WHEN #tag = 'rm01' THEN '03' ELSE ''
END) + '_dat_badge'
AND DateTime >= DATEADD(HH, -12, GETDATE())
AND DateTime <= GETDATE()
I want to find if query does not return any results, then print 'no records found' else execute the query.
Here is my query,
select case when exists (
SELECT CAST(dm.[ID] AS VARCHAR(100)) as ID, case when dm.[Que_Type] = 0 then 'Valid' else 'Invalid' end [Type],
dm.[Name_List], t.[Name], dm.[FromDate], dm.[ToDate] FROM tblDays dm(nolock)
inner join (select pr.ID, pr.name from tblProduct pr(nolock)) as t
on dm.TradeID = t.ID where 1=1 and dm.ToDate between GETDATE() and DATEADD(dd, 15, GETDATE()))
then 'ok'
else 'no records'
end
In this query, I want to execute the query instead of printing 'ok'. How can I do that?
You could use an if statement along with exists
Since the conditional check is just to see if any records are returned, there is no need to select all those columns, so we just select 1. If records are found, the if tests true, and we'll run the sql statement. If no records are found, we'll drop to the else block and print 'no records'.
This may work for you:
IF(
exists(
select 1
FROM tblDays dm(nolock)
inner join (select pr.ID, pr.name from tblProduct pr(nolock)) as t
on dm.TradeID = t.ID
where 1=1
and dm.ToDate between GETDATE() and DATEADD(dd, 15, GETDATE())
)
)
BEGIN
SELECT CAST(dm.[ID] AS VARCHAR(100)) as ID
, case when dm.[Que_Type] = 0 then 'Valid' else 'Invalid' end [Type]
, dm.[Name_List]
, t.[Name]
, dm.[FromDate]
, dm.[ToDate]
FROM tblDays dm(nolock)
inner join (select pr.ID, pr.name from tblProduct pr(nolock)) as t
on dm.TradeID = t.ID
where 1=1
and dm.ToDate between GETDATE() and DATEADD(dd, 15, GETDATE())
END
ELSE
BEGIN
print 'no records'
END
You could use ##ROWCOUNT:
According to BOL:
Returns the number of rows affected by the last statement.
SELECT
CAST(dm.[ID] AS VARCHAR(100)) AS ID,
CASE WHEN dm.[Que_Type] = 0 THEN 'Valid' ELSE 'Invalid' END AS [Type],
dm.[Name_List],
t.[Name],
dm.[FromDate],
dm.[ToDate]
FROM tblDays dm(NOLOCK)
INNER JOIN (
SELECT
pr.ID,
pr.name
FROM tblProduct pr(NOLOCK)
) AS t
ON dm.TradeID = t.ID
WHERE
1 = 1
AND dm.ToDate BETWEEN GETDATE() AND DATEADD(dd, 15, GETDATE())
IF ##ROWCOUNT = 0
PRINT 'No records found.'
Is it possible to do a value assignment with a COUNT() as the when clause?
Like so:
SELECT #value =
CASE
WHEN
COUNT(tableID)
FROM (SELECT TOP (5) tableID FROM table) AS id = 20
THEN 'Looks Good'
END
I basically what to select a variable amount of rows [TOP (#rowCount)], then take action based on the number of rows counted. I'm sure I can do this someway somehow, guessing I'm just missing something in the syntax.
If you're looking for code branching, the following would work:
IF 20 = (select count(*)
from (select top (5) tableID from table) as id)
PRINT 'Looks Good'
ELSE
PRINT '5 will never equal 20'
If you want to get or set a value, one of the following would work:
SELECT case count(*)
when 20 then 'good'
else 'bad'
end
from (select top (5) tableID from table) as id
or
SELECT case
when count(*) > 5 then 'Over 5'
when count(*) < 5 then 'Under 5'
else 'Exactly 5'
end
from (select top (5) tableID from table) as id
Not sure if I understand the question, but maybe try something like
select #val = case when the_number >= 20 then 'Looks good' end
from (
select count(*) the_number from some_table
) x
Assuming you are using at least sql2005 or greater then this will work -
--create a table to test with
create table #TestTable
(
TestTableID int primary key
)
--populate test table
declare #i int = 0;
while #i < 10
begin
insert into #TestTable select #i;
set #i = #i + 1;
end
GO
--now create variables to hold the TOP value and to store the result
declare #a int = 5
,#value varchar(10);
--correct case stmt syntax
set #value = case
when (select count(RecordList) as 'RecordListCount' from (select top (#a) TestTableID as 'RecordList' from #TestTable) as sq) = 20 then 'Looks Good'
else 'Looks Bad'
end;
select #value;
Remember to put the TOP variable in parentheses and to supply aliases for all of the tables and columns.
I hope that helps!
I think I understood your question. You want to know if it is possible to have TOP N rows of table, when N is variable.
If I am right, you will need to specify a column which the table would be ordered.
Then you can use something like:
SELECT *
FROM (
SELECT *, ROW_NUMBER() OVER (ORDER BY COLUMN_NAME) TOPCOL
FROM TABLE_NAME
) A
WHERE TOPCOL <= N
If I am not right, you should edit your question, because it is very hard to understand what you meant