Stored Procedure Date appears long date - date

ALTER PROCEDURE [dbo].[SP_My_Procedured]
AS
BEGIN
SELECT Mission_Time
FROM Mission_Table
WITH (NOLOCK)
WHERE
cast(getdate() as Date)=Mission_Time
END
When i run SP_My_Procedured,
I see Mission_Time as
"2014-01-04 08:35:05.510"
"2014-01-03 10:49:00.697"
But ı want to see like below,
"2014-01-04"
"2014-01-03"
So how can i do this in stored procedure by select ?
Any help will be appreciated.

Cast the value in the SELECT list to Date:
ALTER PROCEDURE [dbo].[SP_My_Procedured]
AS
BEGIN
SELECT
Mission_Time = cast(Mission_Time as Date)
FROM
Mission_Table (NOLOCK)
WHERE
cast(Mission_Time as Date) = cast(getdate() as Date)
END
[BTW: there are dangers to using NO LOCK]
[Also, casting the column to date may not be necessary if it is already of type Date (you don't specify its type). Doing so may result in an appropriate index not being used]

Try
SELECT CONVERT(VARCHAR(10), 'date', 120) AS MissionTime
For more date formats check this

Related

case when in where clause postresql

select service_code,service_cat_code,mobile_no,upper(applicant_name_eng) as name,to_char(license_date,'dd/mm/yyyy')as license_from,to_char(license_valid_upto,'dd/mm/yyyy')as license_to,Upper(license_no),district_code,taluk_code,CONCAT(address_building,', ', address_cityvillage,', ',address_locality,', ',address_landmark,', ',address_street) as address
from mst_license
WHERE cast(license_valid_upto as date) = case
WHEN license_valid_upto < now()
THEN
case
when license_valid_upto = '2021-06-30'
then 1 else 0
END
ELSE
case when license_valid_upto > now()
then 1 else 0
End
END
and Upper(license_no)='1SP146924BJP'
I want license valid should be either greater than now or if license valid less than now it must be with the date ''30/06/2021' but when i use above query i get error
ERROR: operator does not exist: date = integer
LINE 3: WHERE cast(license_valid_upto as date) = case
^
HINT: No operator matches the given name and argument types. You might need to add explicit type casts.
SQL state: 42883
Character: 418
Help me out guys
The main issue you have is that your case statement returns an integer (1 or 0) but you are trying to compare that to a date, which you cannot do as Postgres is a strict data typing. Even if it did work it would always be false (well except for 1969-12-31/1970-01-01). Moreover the case structure is not needed. The best/correct to compare dates is just use date values. Since you did not indicate the data type for column license_valid_upto so based on how it is used I'll assume it is timestamp with timezone as that is what NOW() returns. Your query becomes:
select service_code
, service_cat_code
, mobile_no
, upper(applicant_name_eng) as name
, to_char(license_date,'dd/mm/yyyy')as license_from
, to_char(license_valid_upto,'dd/mm/yyyy')as license_to
, upper(license_no) as license_no
, district_code
, taluk_code
, concat(address_building,', '
,address_cityvillage,', '
,address_locality,', '
,address_landmark,', '
,address_street) as address
from mst_license
where and upper(license_no)='1SP146924BJP'
and ( cast(license_valid_upto as date) > cast( now() as date)
or (cast (icense_valid_upto as date) < cast( now() as date)
and cast (icense_valid_upto as date) = date '2021-06-30'
)
);
Also, learn for format your queries for readability and so you do not need to scroll right. You, and others looking at your queries later will appreciate it later.

Repeated use of parameter for multiple UDF's in FROM throws an invalid column name error

When using multiple table-valued functions in a query like beneath, SSMS throws an error. Also, the [Date] parameter of [PRECALCPAGES_asof] is underlined in red.
I am trying to understand why this fails. I think this might be related to the way the SQL Server engine works. Have looked into documentation on MSDN but unfortunately I do not know what to look for. Why is this caused and is there a way around it?
Query
SELECT
[Date]
, COUNT(*)
FROM
[Warehouse].[dbo].[DimDate]
CROSS APPLY
[PROJECTS_asof]([Date])
INNER JOIN
[PRECALCPAGES_asof]([Date]) ON [PRECALCPAGES_asof].[PROJECTID] = [PROJECTS_asof].[PROJECTID]
GROUP BY
[Date]
Error
Msg 207, Level 16, State 1, Line 9
Invalid column name 'Date'.
Functions
CREATE FUNCTION [ProfitManager].[PROJECTS_asof]
(
#date DATETIME
)
RETURNS TABLE AS
RETURN
(
SELECT
[PROJECTID]
, [PROJECT]
, ...
FROM
Profitmanager.[PROJECTS_HISTORY]
WHERE
[RowStartDate] <= #date
AND
[RowEndDate] > #date
)
GO
CREATE FUNCTION [ProfitManager].[PRECALCPAGES_asof]
(
#date DATETIME
)
RETURNS TABLE AS
RETURN
(
SELECT
[PAGEID]
, [PAGENAME]
, ...
FROM
Profitmanager.[PRECALCPAGES_HISTORY]
WHERE
[RowStartDate] <= #date
AND
[RowEndDate] > #date
)
GO
I think you can't use fields from tables as parameters to a function in a join. You should use cross apply.
SELECT
[Date]
, COUNT(*)
FROM
[Warehouse].[dbo].[DimDate]
CROSS APPLY
[PROJECTS_asof]([Date])
CROSS APPLY
[PRECALCPAGES_asof]([Date])
WHERE
[PRECALCPAGES_asof].[PROJECTID] = [PROJECTS_asof].[PROJECTID]
GROUP BY
[Date]

Unable to use variable in DATEADD(#pinterval, #pinterval, #DayPlus)

DECLARE #pinterval INT = 1, #DayPlus DATETIME = '2016-07-01', #datepart VARCHAR(20) = 'MONTH'
SET #DayPlus = DATEADD(#datepart, #pinterval, #DayPlus)
SELECT #DayPlus
Do we have any alternative to accomplish task ? I have to do it in loop so I can't define it every time based on interval value. Only date part is not acceptable as variable because if I use as
DATEADD(MONTH, #pinterval, #DayPlus)
then it's working fine. Not sure but I can understand the issue but I am seeking for the quick solution. I have visited the web but didn't get exact solution.
It's not possible to substitute a variable for the first argument to DATEADD1, since what is wanted here is a name, not a string.
About the best you can do is a CASE expression:
SET #DayPlus =
CASE #datepart
WHEN 'MONTH' THEN DATEADD(MONTH, #pinterval, #DayPlus)
WHEN 'YEAR' THEN DATEADD(YEAR, #pinterval, #DayPlus)
WHEN 'DAY' THEN DATEADD(DAY, #pinterval, #DayPlus)
--TODO - add all parts you might wish to use
END
1This is even stated in the documentation:
User-defined variable equivalents are not valid.
if this is only the way then I have to repeat this for more than 10times
No, use CROSS APPLY
#Shnugo it sounds good, can you please help me by placing the complete code as an answer. Please !!
About CROSS APPLY: generate something like a variable dynamically
CREATE TABLE dbo.Test(ID INT, SomeDate DATE);
GO
INSERT INTO dbo.Test VALUES(1,{d'2017-01-01'}),(2,{d'2017-02-02'})
GO
DECLARE #Intervall VARCHAR(100)='DAY';
DECLARE #Count INT=1
SELECT dbo.Test.*
,t.AddedDate
FROM dbo.Test
CROSS APPLY(SELECT CASE #Intervall WHEN 'MONTH' THEN DATEADD(MONTH,#Count,SomeDate)
WHEN 'DAY' THEN DATEADD(DAY,#Count,SomeDate)
ELSE SomeDate END AS AddedDate) AS t;
GO
DROP TABLE dbo.Test;
You could use dynamic SQL:
DECLARE #pinterval INT = 1,
#DayPlus DATETIME = '2016-07-01',
#datepart NVARCHAR(20) = 'MONTH'
DECLARE #sql NVARCHAR(MAX) = N'SET #DayPlus = DATEADD('+#datepart+', #pinterval, #DayPlus)',
#params NVARCHAR(MAX) = N'#DayPlus DATETIME OUTPUT, #pinterval INT'
EXEC sp_executesql #sql, #params, #pinterval = #pinterval, #DayPlus = #DayPlus OUTPUT
SELECT #DayPlus
sp_executesql is used for 2 reasons:
to minimize SQL injections risk, it will not eliminate it because of #datepart
it will make sure your dynamic query's plan is going to be cached - which might be beneficial with simple queries (where query time vs compilation time matters)

how to add date in Teradata?

Hi i want to add 01/01/1970 to a column ,datatype of last_hit_time_gmt is bigint ,when i run the below query i am getting data type
last_hit_gmmt
does not match a defined datatype name.
select
distinct STG.OMN_APND_KEY,
STG.last_hit_time_gmt,
IIF(STG.last_hit_time_gmt <>0,ADD_TO_DATE(TO_DATE('01/01/1970', 'DD/MM/YYYY'),'SS',cast(STG.last_hit_time_gmt as DATE ),NULL)
from EDW_STAGE_CDM_SRC.STG_OMNITUREDATA STG
WHERE
UPPER(STG_OMNITUREDATA.EVAR41) IN
('CONS_SUPP: CONSUMER','STORE','PURCHASE') and
STG.OMN_APND_KEY='61855975'
please help me..
The query and data type is incompatible with Teradata.
As stated in the comments you may want to use "CASE" instead of "IFF". The general format is
CASE WHEN *condition* THEN *result_if_true*
ELSE *result_if_false*
END as *ColumnName*
editing based on comment response
So in your query example the case statement can be used like...
select distinct STG.OMN_APND_KEY
,STG.last_hit_time_gmt
,CASE WHEN STG.last_hit_time_gmt = 0 THEN NULL
ELSE DATE '1970-01-01'
END AS YourColName
FROM EDW_STAGE_CDM_SRC.STG_OMNITUREDATA STG
WHERE UPPER(STG_OMNITUREDATA.EVAR41) IN
('CONS_SUPP: CONSUMER','STORE','PURCHASE') and
STG.OMN_APND_KEY='61855975'
Also, if you are merely just trying to update the field STG.last_hit_time_gmt, why not just use two simple UPDATE statements?
UPDATE EDW_STAGE_CDM_SRC.STG_OMNITUREDATA
SET STG.last_hit_time_gmt = DATE '1970-01-01'
WHERE STG.last_hit_time_gmt <> 0
AND UPPER(STG_OMNITUREDATA.EVAR41) IN
('CONS_SUPP: CONSUMER','STORE','PURCHASE')
AND STG.OMN_APND_KEY='61855975';
UPDATE EDW_STAGE_CDM_SRC.STG_OMNITUREDATA
SET STG.last_hit_time_gmt = NULL
WHERE STG.last_hit_time_gmt = 0
AND UPPER(STG_OMNITUREDATA.EVAR41) IN
('CONS_SUPP: CONSUMER','STORE','PURCHASE')
AND STG.OMN_APND_KEY='61855975';

Convert a string representing a timestamp to an actual timestamp in PostgreSQL?

In PostgreSQL: I convert string to timestamp with to_timestamp():
select * from ms_secondaryhealthcarearea
where to_timestamp((COALESCE(update_datetime, '19900101010101'),'YYYYMMDDHH24MISS')
> to_timestamp('20121128191843','YYYYMMDDHH24MISS')
But I get this error:
ERROR: syntax error at end of input
LINE 1: ...H24MISS') >to_timestamp('20121128191843','YYYYMMDDHH24MISS')
^
********** Error **********
ERROR: syntax error at end of input
SQL state: 42601
Character: 176
Why? How to convert a string to timestamp?
One too many opening brackets. Try this:
select *
from ms_secondaryhealthcarearea
where to_timestamp(COALESCE(update_datetime, '19900101010101'),'YYYYMMDDHH24MISS') >to_timestamp('20121128191843','YYYYMMDDHH24MISS')
You had two opening brackets at to_timestamp:
where to_timestamp((COA.. -- <-- the second one is not needed!
#ppeterka has pointed out the syntax error.
The more pressing question is: Why store timestamp data as string to begin with? If your circumstances allow, consider converting the column to its proper type:
ALTER TABLE ms_secondaryhealthcarearea
ALTER COLUMN update_datetime TYPE timestamp
USING to_timestamp(update_datetime,'YYYYMMDDHH24MISS');
Or use timestamptz - depending on your requirements.
Another way to convert a string to a timestamp type of PostgreSql is the above,
SELECT to_timestamp('23-11-1986 06:30:00', 'DD-MM-YYYY hh24:mi:ss')::timestamp without time zone;
I had the same requirement as how I read the title. How to convert an epoch timestamp as text to a real timestamp. In my case I extracted one from a json object. So I ended up with a timestamp as text with milliseconds
'1528446110978' (GMT: Friday, June 8, 2018 8:21:50.978 AM)
This is what I tried. Just the latter (ts_ok_with_ms) is exactly right.
SELECT
data->>'expiration' AS expiration,
pg_typeof(data->>'expiration'),
-- to_timestamp(data->>'expiration'), < ERROR: function to_timestamp(text) does not exist
to_timestamp(
(data->>'expiration')::int8
) AS ts_wrong,
to_timestamp(
LEFT(
data->>'expiration',
10
)::int8
) AS ts_ok,
to_timestamp(
LEFT(
data->>'expiration',
10
)::int8
) + (
CASE
WHEN LENGTH(data->>'expiration') = 13
THEN RIGHT(data->>'expiration', 3) ELSE '0'
END||' ms')::interval AS ts_ok_with_ms
FROM (
SELECT '{"expiration": 1528446110978}'::json AS data
) dummy
This is the (transposed) record that is returned:
expiration 1528446110978
pg_typeof text
ts_wrong 50404-07-12 12:09:37.999872+00
ts_ok 2018-06-08 08:21:50+00
ts_ok_with_ms 2018-06-08 08:21:50.978+00
I'm sure I overlooked a simpler version of how to get from a timestamp string in a json object to a real timestamp with ms (ts_ok_with_ms), but I hope this helps nonetheless.
Update: Here's a function for your convenience.
CREATE OR REPLACE FUNCTION data.timestamp_from_text(ts text)
RETURNS timestamptz
LANGUAGE SQL AS
$$
SELECT to_timestamp(LEFT(ts, 10)::int8) +
(
CASE
WHEN LENGTH(ts) = 13
THEN RIGHT(ts, 3) ELSE '0'
END||' ms'
)::interval
$$;