Desired output: change the date 2020-06-15 to a string that reads 2020-06
In BigQuery StandardSQL the following works
SELECT
CONCAT(
CAST( EXTRACT(YEAR FROM date) ) AS STRING, '-', CAST( EXTRACT(MONTH FROM date) AS STRING)
) as year_date
FROM
table
This gives you '20202-06' in BigQuery.
In PostgreSQL I get the following error
ERROR: function concat(character varying, "unknown", character varying) does not exist
I've tried all sorts with this and still can't get the right answer.
e.g.
concat(extract(year from date)::text, '-', extract(month from date)::text ) as year_date
concat(cast(extract(year from date) as varchar(16)), '-', cast(extract(month from date) as varchar(16)) ) as year_date,
However, I still end up with the same error?
Many thanks
Use to_char to format a dates, timestamps, and numbers.
# select to_char('2020-06-15'::date, 'YYYY-MM');
to_char
---------
2020-06
Something like:
SELECT
CONCAT(
CAST( EXTRACT(YEAR FROM current_date) AS varchar), '-', CAST( EXTRACT(MONTH FROM current_date) AS varchar)
) as year_date;
year_date
-----------
2020-6
Hi all I have a stored procedure with two parameters #Startdate and #Enddate. When i execute the procedure i get data.
Now i added a parameter and it has list of values. So i added a split function and added in the WHERE clause. Now after making the changes when i execute my SP i do not get any data. I tried commenting out the 3rd Parameter from the WHERE clause and now i see the data again. Not sure what is happening. Any advice is greatly appreciated.
I have tried different split functions and Charindex(','+cast(tableid as varchar(8000))+',', #Ids) > 0 and nothing has worked.
Thanks
NOTE: The concatenation and splitting of parameter values is a poor design for performance reasons and, most importantly, very susceptible to SQL injection attacks. Please research some alternatives. If you must proceed down this path...
There are a great many split functions out there, but I used this one here to illustrate a possible solution.
CREATE FUNCTION [dbo].[fnSplitString]
(
#string NVARCHAR(MAX),
#delimiter CHAR(1)
)
RETURNS #output TABLE(splitdata NVARCHAR(MAX)
)
BEGIN
DECLARE #start INT, #end INT
SELECT #start = 1, #end = CHARINDEX(#delimiter, #string)
WHILE #start < LEN(#string) + 1 BEGIN
IF #end = 0
SET #end = LEN(#string) + 1
INSERT INTO #output (splitdata)
VALUES(SUBSTRING(#string, #start, #end - #start))
SET #start = #end + 1
SET #end = CHARINDEX(#delimiter, #string, #start)
END
RETURN
END
GO
It's unclear, from your question, if you need to filter your results based on an int, varchar or various other data types available, but here are two options (and probably the most common).
DECLARE #TableOfData TABLE
(
ID_INT INT,
ID_VAR VARCHAR(100),
START_DATE DATETIME,
END_DATE DATETIME
)
DECLARE #StartDate DATETIME
DECLARE #EndDate DATETIME
DECLARE #Ids VARCHAR(1000)
DECLARE #Delimiter VARCHAR(1)
SET #Delimiter = ','
SET #StartDate = GETDATE()
SET #EndDate = DATEADD(HH, 1, GETDATE())
SET #Ids = '1,2,4'
--Create some test data
INSERT INTO #TableOfData
SELECT 1, '1', GETDATE(), DATEADD(MI, 1, GETDATE()) --In our window of expected results (date + id)
UNION SELECT 2, '2', GETDATE(), DATEADD(D, 1, GETDATE()) --NOT in our window of expected results b/c of date
UNION SELECT 3, '3', GETDATE(), DATEADD(MI,2, GETDATE()) --NOT in our expected results (id)
UNION SELECT 4, '4', GETDATE(), DATEADD(MI,4, GETDATE()) --In our window of expected results (date + id)
--If querying by string, expect 2 results
SELECT TD.*
FROM #TableOfData TD
INNER JOIN dbo.fnSplitString(#Ids, #Delimiter) SS
ON TD.ID_VAR = SS.splitdata
WHERE START_DATE >= #StartDate
AND END_DATE <= #EndDate
--If querying by int, expect 2 results
SELECT TD.*
FROM #TableOfData TD
INNER JOIN dbo.fnSplitString(#Ids, #Delimiter) SS
ON TD.ID_INT = CONVERT(int, SS.splitdata)
WHERE START_DATE >= #StartDate
AND END_DATE <= #EndDate
You cannot use a parameter with a list directly in your query filter. Try storing that separated data into a table variable or temp table and call that in your query or use dynamic SQL to write your query if you don't want to use table variable or temp tables.
I have to read dates from a varchar column with the following possible patterns ( month/day/year ):
1/1/2005
1/13/2005
10/9/2005
10/13/2005
What is the correct way to read the day part of those dates with T-SQL?
Casting to date and using day() would be the correct approach imo:
declare #t table (string varchar(10))
insert #t values ('1/1/2005'),('1/13/2005'),('10/9/2005'),('10/13/2005')
select day(cast(string as date)) as the_day from #t
Would give:
the_day
-----------
1
13
9
13
An alternative if you want to avoid casting would be to use thesubstringandcharindexfunctions:
select
substring(
string,
charindex('/', string)+1,
charindex('/', string, charindex('/', string)+1)-charindex('/', string)-1
)
from #t
I need to get the tsql datetime of the first day of the current month to use in a query.
I have come up with
declare #StartDate datetime
set #StartDate = cast( MONTH( getdate()) as char(2))+ '/1/'
+ cast( Year( getdate()) as char(4))
select #StartDate
But was wondering about a better way to do this.
Suggestions?
How about this:
SELECT DATEADD(month, DATEDIFF(month, 0, getdate()), 0) AS FirstOfMonth
select dateadd(month, datediff(month, 0, getdate()), 0)
I have scripts for adding columns to tables which worked.
When I run scripts to alter views with the new column the script fails because the columns are not recognized
Msg 207, Level 16, State 1, Procedure UniqueTempDispositions, Line 76
Invalid column name 'servicerequestid'.
Msg 207, Level 16, State 1, Procedure UniqueTempDispositions, Line 47
Invalid column name 'servicerequestid'.
Msg 207, Level 16, State 1, Procedure MergeDispositions, Line 54
Invalid column name 'ServiceRequestID'.
Msg 207, Level 16, State 1, Procedure NonPIICachedDispositions, Line 18
Invalid column name 'ServiceRequestID'.
Any reason why? Am I missing something?
I've started and stopped the server, I've relogged in to no avail.
ORIGINAL SCRIPT:
alter view
dbo.UniqueTempDispositions
as
SELECT QuotaGroup, Country, ServiceGroup, Language, ContactChannel, TrackingID, CONVERT(DATETIME, CaseClosedDate) AS casecloseddate, MSFTRep, CustEmail,
CustPhone, CustomerName, ProductFamily, ProductSubType, CONVERT(DATETIME, CandidateReceivedDate) AS candidatereceiveddate, CONVERT(INT, SurveyMode)
AS surveymode, CONVERT(DATETIME, SurveyWaveStartDate) AS surveywavestartdate, CONVERT(DATETIME, SurveyInvitationDate) AS surveyinvitationdate,
CONVERT(DATETIME, SurveyReminderDate) AS surveyreminderdate, CONVERT(DATETIME, SurveyCompleteDate) AS surveycompletedate, CONVERT(DATETIME,
OptOutDate) AS optoutdate, CONVERT(DATETIME, SurveyWaveEndDate) AS surveywaveenddate, CONVERT(INT, DispositionCode) AS dispositioncode, SurveyName,
SurveyVendor, COUNT(*) AS countofunique, BusinessUnitName, UploadId, MIN(LineNumber) AS LineNumber, BusinessUnitSubgroup, ServiceRequestID
FROM DispositionReporting.dbo.tempDispositions AS td
GROUP BY QuotaGroup, Country, ServiceGroup, Language, ContactChannel, TrackingID, CONVERT(DATETIME, CaseClosedDate), MSFTRep, CustEmail, CustPhone,
CustomerName, ProductFamily, ProductSubType, CONVERT(DATETIME, CandidateReceivedDate), CONVERT(INT, SurveyMode), CONVERT(DATETIME,
SurveyWaveStartDate), CONVERT(DATETIME, SurveyInvitationDate), CONVERT(DATETIME, SurveyReminderDate), CONVERT(DATETIME, SurveyCompleteDate),
CONVERT(DATETIME, OptOutDate), CONVERT(DATETIME, SurveyWaveEndDate), CONVERT(INT, DispositionCode), SurveyName, SurveyVendor, BusinessUnitName,
UploadId, BusinessUnitSubgroup, ServiceRequestID
go
I ended up dropping and re-adding the view which worked, just don't understand the other way around:
use DispositionReporting
go
drop view dbo.UniqueTempDispositions
go
create view
dbo.UniqueTempDispositions
as
SELECT QuotaGroup, Country, ServiceGroup, Language, ContactChannel, TrackingID, CONVERT(DATETIME, CaseClosedDate) AS casecloseddate, MSFTRep, CustEmail,
CustPhone, CustomerName, ProductFamily, ProductSubType, CONVERT(DATETIME, CandidateReceivedDate) AS candidatereceiveddate, CONVERT(INT, SurveyMode)
AS surveymode, CONVERT(DATETIME, SurveyWaveStartDate) AS surveywavestartdate, CONVERT(DATETIME, SurveyInvitationDate) AS surveyinvitationdate,
CONVERT(DATETIME, SurveyReminderDate) AS surveyreminderdate, CONVERT(DATETIME, SurveyCompleteDate) AS surveycompletedate, CONVERT(DATETIME,
OptOutDate) AS optoutdate, CONVERT(DATETIME, SurveyWaveEndDate) AS surveywaveenddate, CONVERT(INT, DispositionCode) AS dispositioncode, SurveyName,
SurveyVendor, COUNT(*) AS countofunique, BusinessUnitName, UploadId, MIN(LineNumber) AS LineNumber, BusinessUnitSubgroup, ServiceRequestID
FROM DispositionReporting.dbo.tempDispositions AS td
GROUP BY QuotaGroup, Country, ServiceGroup, Language, ContactChannel, TrackingID, CONVERT(DATETIME, CaseClosedDate), MSFTRep, CustEmail, CustPhone,
CustomerName, ProductFamily, ProductSubType, CONVERT(DATETIME, CandidateReceivedDate), CONVERT(INT, SurveyMode), CONVERT(DATETIME,
SurveyWaveStartDate), CONVERT(DATETIME, SurveyInvitationDate), CONVERT(DATETIME, SurveyReminderDate), CONVERT(DATETIME, SurveyCompleteDate),
CONVERT(DATETIME, OptOutDate), CONVERT(DATETIME, SurveyWaveEndDate), CONVERT(INT, DispositionCode), SurveyName, SurveyVendor, BusinessUnitName,
UploadId, BusinessUnitSubgroup, ServiceRequestID
go
exec sp_refreshview 'dbo.UniqueTempDispositions'
go
Take a look at how to make sure that the view will have the underlying table changes by using sp_refreshview
Did you run sp_refreshview against the views after you made changes to the tables?