How to convert int to date in MS Sql - sql-server-2008

I have an integer in one of the column as 123114, which I need to convert as DATE format (12/31/2014). How can I do it? I even tried to convert it to datetime and then date, but that is not working either. I am running out with errors. Can anyone help me in this.
Thanks,
Rahul

declare #yourdate int
select #yourdate = 20141231
select CONVERT (date,convert(char(8),#yourdate))
try this..

declare
#testDate as int = '123114',
#StringDate as Char(6)
set #StringDate = Cast(#testDate as Char(6))
select
ActualDate = (Substring(#StringDate,1,2) + '/' + Substring(#StringDate,3,2) + '/20' + Substring(#StringDate,5,2))
This would assume that the int was formatted as mmddyy, requiring a leading 0 when m < 10 as mentioned previously.

Without seeing a query, it's hard to give you a definite answer. Presuming your integers are always in a mmddyy format, this should work:
declare #a int = 121314
declare #b varchar(10)
select #b = cast(#a as varchar(10))
if len(#b) = 6 --mmddyy
begin
select cast(substring(#b,1,2) + '-' + substring(#b,3,2) + '-' +substring(#b,5,2) as date) as castDate --depends on database collation
select convert(date, substring(#b,1,2) + '/' + substring(#b,3,2) + '/' +substring(#b,5,2), 1) as convertedDate
end
else
begin
print 'need something more complicated here'
end
You'll definitely want some sort of else condition regardless, to handle bad data, unless your values are pretty tightly constrained.

Related

Getting an error creating SQL Function (cannot convert to int) when no ints are expected

I am needing to grab data from one table and use a relationship to place it into another table. Long story short, I need to get back an array of IDs so I created a function to return them. I am only retrieving data which is IDs so all int values. The problem is when I invoke my function I get the error:
Conversion failed when converting the varchar value '/' to data type int.
But everything is cast as varchar so I have NO idea why this is happening. I know its dirty code but it is a high priority project with a tight deadline so I just need it to work. I am using SQL Server 2012. Any thoughts?
Function:
CREATE FUNCTION FactPersonList (#FactID varchar(100),
#delimiter char(1))
RETURNS varchar(8000)
AS
BEGIN
DECLARE #CharIDList varchar(8000)
DECLARE #id int
DECLARE #FinalTable TABLE (
factid int,
charid int
)
SET #CharIDList = CHAR(08) + #delimiter
INSERT INTO #FinalTable
SELECT DISTINCT
#FactID,
CharacterId
FROM KeyFactsCharacters
WHERE KeyFactID = #FactID
WHILE ((SELECT
COUNT(*)
FROM #FinalTable)
> 0)
BEGIN
SET #Id = (SELECT TOP 1
charid
FROM #FinalTable)
SET #CharIDList = CAST(#CharIDList + #Id + #delimiter AS varchar(8000))
END
SET #CharIDList = CAST(#CharIDList + CHAR(08) + '~' AS varchar(8000))
RETURN CAST(#CharIDList AS varchar(8000))
END
I invoke it using this:
SELECT dbo.FactPersonList(KeyFact.KeyFactId, '/') FROM KeyFactsCharacters, KeyFact
I'm not familiar with MS SQL (experience almost exclusively in MySQL), but I would guess that #CharIDList + #Id + #delimiter is causing the error; since #Id is defined as an int, MS SQL may be trying to coerce the other operands to int values as well (for addition rather than concatenation).

Remove Non Numeric Values Within SQL Select Statement

I have a value in a database column VALUE:
C_4327
I need to strip the non numeric text from this so that it just leaves the numbers. I have tried using the REPLACE function within SQL but not I don't want to replace, just strip them out. I was previously using PHP to do this:
preg_replace("/[^0-9]/","",$row['VALUE']);
I'm retrieving the value in a SELECT statement.
Your help would be appreciated.
Thanks in advance
If you want to get the number at the end of the string, you can use the following arcane approach:
select reverse(reverse(value) + 0) as NumberAtEnd;
In your case:
value ='C_4327'
reverse(value) = '7234_C'
reverse(value) + 0 = 7234
reverse(reverse(value) + 0) = '4327'
you can create a Function like that/.
CREATE FUNCTION GetNumeric
(
#strAlphaNumeric VARCHAR(256))
RETURNS VARCHAR(256)
AS BEGIN
DECLARE #intAlpha INT
SET #intAlpha = PATINDEX('%[^0-9]%', #strAlphaNumeric)
BEGIN
WHILE
#intAlpha > 0
BEGIN
SET #strAlphaNumeric = STUFF(#strAlphaNumeric, #intAlpha, 1, '' )
SET #intAlpha = PATINDEX('%[^0-9]%', #strAlphaNumeric )
END
END
RETURN ISNULL(#strAlphaNumeric,0)
END
GO
then call the function as follows
SELECT GetNumeric('123456789blahblahblah') AS filedname FROM your_table
you will get the answer : 123456789
simple way: how about substring...
select substr( value, 3 ) from mytable;
it works on your example - but not sure if your real data is more complicated.

SSIS convert date in int format to Date (yyyy/mm/dd hh:mi:ss)

In SSIS I have date in int format 2012123023
need to convert it into 2012/12/30 23:00:00
please help!
I have used this function in SQL Server, although, I'm not SSIS expert so I'm not sure how you implement it in the SSIS package.
I would assume that you can create the function in the database and then call it from SSIS.
Edited to work for your test case, it does assume that the number is always in the same format though.
--SELECT [dbo].[ConvertIntToDate](2012123023)
-- =============================================
-- Author: Richard Andrews
-- Create date: 12/10/2012
-- Description: Safely attempts to convert an int into a date
-- =============================================
ALTER FUNCTION [dbo].[ConvertIntToDate]
(
#InputNumber INT
)
RETURNS DATETIME
AS
BEGIN
IF #InputNumber IS NULL
BEGIN
RETURN NULL
END
DECLARE #Result DATETIME
DECLARE #StringDate NVARCHAR(50)
SET #StringDate = CAST(#InputNumber AS NVARCHAR(50))
IF LEN(#StringDate) <> 10
BEGIN
RETURN NULL
END
DECLARE #FormattedStringDate NVARCHAR(50)
SET #FormattedStringDate = SUBSTRING(#StringDate, 1, 4)
+ '-' + SUBSTRING(#StringDate, 5, 2)
+ '-' + SUBSTRING(#StringDate, 8, 2)
+ ' ' + SUBSTRING(#StringDate, 9, 2) + ':00'
IF ISDATE(#FormattedStringDate) = 0
BEGIN
RETURN NULL
END
SET #Result = CONVERT(DATETIME, #FormattedStringDate)
RETURN #Result
END
it doesn't look like a valid SQL Server date format (at least one that SQL Server would understand).
If you are 100% sure that the string would always be on this format, you can do something like
DECLARE #mydate VARCHAR(20)
SET #mydate=2012123023
SELECT
CAST(
SUBSTRING(#mydate,1,4)+'-'+SUBSTRING(#mydate,5,2)+'-'+SUBSTRING(#mydate,7,2)+' '+SUBSTRING(#mydate,9,2)+':00'
AS DATETIME)

MySQL - min_word_length 2 or 3 - need a count

I am trying to decide whether to set min_word_length to be 2 or 3 on my new MySQL instance, so i figure if I count the number of 2 letter words in the column to be indexed it will give an indication of the right answer.
So, question is, is it possible using a SQL query to count the number two letter words within a column?
Not tested, but could you try
SELECT SUM(
CASE WHEN yourColumn REGEXP '[[:<:]][a-zA-Z]{2}[[:>:]]'
THEN 1
ELSE 0 END
) AS matches
FROM ...
Although I think, that it might only count if a 2-character-word is in a row, not how many times in one row.
UPDATE: Tested and it works like I thought, so please just ignore this answer.
The LEN() function returns the length of the value in a text field.
SELECT LEN(column_name) FROM table_name
The COUNT(*) function returns the number of records in a table:
SELECT COUNT(column_name) FROM table_name
So your query should be something like this :
SELECT COUNT(column_name) FROM table_name
WHERE LEN(column_name)=2
UPDATE:
Ok sorry I guess I misunderstood you. In the case you want it I'm afraid there is no build in functions to do what you want it to do. So you have to make a function on your own. Something like this should work:
CREATE FUNCTION [dbo].[WordCount] ( #InputString VARCHAR(4000) )
RETURNS INT
AS
BEGIN
DECLARE #Index INT
DECLARE #Char CHAR(1)
DECLARE #PrevChar CHAR(1)
DECLARE #WordCount INT
DECLARE #CharCount INT
SET #Index = 1
SET #WordCount = 0
WHILE #Index <= LEN(#InputString)
BEGIN
SET #Char = SUBSTRING(#InputString, #Index, 1)
SET #CharCount = #CharCount + 1
SET #PrevChar = CASE WHEN #Index = 1 THEN ' '
ELSE SUBSTRING(#InputString, #Index - 1, 1)
END
IF #PrevChar = ' '
SET #CharCount = 1
END
IF #Char = ' ' AND #CharCount < 3 AND #CharCount > 1
SET #WordCount = #WordCount + 1
SET #Index = #Index + 1
END
RETURN #WordCount
END
Now I have not tested it so you have to test it on your own but it should work. It will return all 2 letter words in the selected string. To get the 3 letters words just change
IF #Char = ' ' AND #CharCount < 4 AND #CharCount > 2
I hope this helps.

Conversion of date from character string error

I have a select statement which contains a number, description, date. when i try to add my date to the statement and run it i get a date conversion from character string error and i am not really sure how to go about it.
DECLARE #parties AS TABLE (
PartyId UNIQUEIDENTIFIER
, Cases NVARCHAR(MAX)
, CaseTypes VARCHAR(MAX)
, Assignment DateTime)
DECLARE #cases NVARCHAR(MAX)
DECLARE #casetypes VARCHAR(MAX)
DECLARE #assignment DateTime
DECLARE #linebreak AS VARCHAR(2)
SET #cases = NULL
SET #casetypes = NULL
SET #assignment = NULL
SET #linebreak = CHAR(13) + CHAR(10)
SELECT #cases = COALESCE(#cases+ #linebreak + C.CaseNumber, C.CaseNumber)+"-"+CT.[Description]+"-"+A.DateOn
FROM [Case] C
INNER JOIN CaseType CT ON C.CaseTypeId = CT.CaseTypeId
INNER JOIN #partyCases PC ON C.CaseId = PC.CaseId
INNER JOIN Appointment A ON C.CaseId = A.CaseId
WHERE PC.PartyId = #partyId
The error occurs after adding A.DateOn to my select statement and running it - any suggestions will be great. Thanks!
SQL returns Date values as datetime and such values can not be implicitly used as strings (varchars). You will have to explicitly convert or cast them. So, change your select statement in either of the 2 ways below:
SELECT #cases = COALESCE(#cases+ #linebreak + C.CaseNumber, C.CaseNumber)+"-"+CT.[Description]+"-"+CONVERT(varchar, A.DateOn)
OR
SELECT #cases = COALESCE(#cases+ #linebreak + C.CaseNumber, C.CaseNumber)+"-"+CT.[Description]+"-"+CAST(A.DateOn as varchar)
CONVERT has a slight advantage - you can apply formatting on the date, if you want.