Transact SQL :: Convert Datetime To Integer?

Aug 5, 2013

I have this datetime: '2002-12-20 11:59:59'

I want to convert this to date (yyyy-mm-dd) to integer

This works fine for: SELECT CONVERT(INT, GETDATE())

But it doesn't work here: SELECT CONVERT(INT, '2002-12-20 11:59:59')

I want to convert date to integer without passing through any varchar conversion/result.

View 6 Replies


ADVERTISEMENT

DB Design :: Convert Integer Date (MMDDYY) And Integer Time (HHMMSS) To DateTime Format?

Jul 20, 2015

Working on a new database where the Date and Time are stored in a Date Time Field.

Then working on an OLDER database file within the same SQL Database contains these 2 items as integers:

transDate = "71615" (July 16, 2015)
transTime = "12345" (01:23:45 AM)

How do we convert both of them into a single SQL DateTime field such as "2015-07-16 01:23:45.000" so that it can be used in a join restricting to a date time in a different SQL File that properly has the DateTime in it?

This works well for converting the transDate Part in the select statement:

   dbo.IntegerToDate(at.transDate) as transDate

   * That returns: "2015-07-16 00:00:00.000"

* The resulting data must work directly in a Microsoft SQL Server Management Studio Query using either using the "on" statement or part of the "where" clause. In other words, NOT as a stored procedure!

Also must be able to be used as a date difference calculation when comparing the 2 files Within say + or - 5 seconds.

View 3 Replies View Related

Convert Datetime To Integer Value As Shown Within Brackets

Dec 23, 2014

Iwant to convert the datetime to the integer value as shown within the brackets.

----2014-12-21 0:00:00 (1419091200000)

View 1 Replies View Related

Transact SQL :: Convert String To Datetime

Jul 28, 2015

I have below string, which is a datetime value

I want to convert it into datetime data type and insert into table

DECLARE @Date VARCHAR(100)

SET @Date='10312013122642'

View 8 Replies View Related

Transact SQL :: How To Convert CCYYMMDDHHMMSS To Datetime Format

Aug 20, 2015

I have a data column coming in from a 3rd party vendor in the format of CCYYMMDDHHMMSS. How can I convert this data to a [datetime] format?

CAST(CAST([TransactionDate] AS CHAR(14)) AS datetime)

Is that correct?

View 7 Replies View Related

Transact SQL :: Convert Comma Separated String Values Into Integer Values

Jul 28, 2015

I have a string variable

string str1="1,2,3,4,5";

I have to use the above comma separated values into a SQL Search query whose datatype is integer. How would i do this Search query in the IN Operator of SQL Server. My query is :

declare @id varchar(50)
set @id= '3,4,6,7'
set @id=(select replace(@id,'''',''))-- in below select query Id is of Integer datatype
select *from ehsservice where id in(@id)

But this query throws following error message:

Conversion failed when converting the varchar value '3,4,6,7' to data type int.

View 4 Replies View Related

Transact SQL :: Convert Int To Time And Concatenate It With Datetime Field?

Sep 16, 2015

I have a datetime field for e.g 2015-09-15 00:00:00.000 and an integer field for e.g.100809.

The integer field is actually a time value as in hours,minutes,seconds. For e.g. the value

100809 means
10-hours
08-minutes
09-seconds

I need to combine the datetime and the int field to get the output as below

2015-09-15 10:08:09

View 7 Replies View Related

Integer To Datetime UDF

Oct 5, 2007

Trying to write the most effective UDF to convert INT to Datetime.
We have a column from a table on AS400 that is a INT type. Some are 4, 5, 6 ,7 digits. I have the 4 digits right. I need to fix it for 5 and 6 digits.


ALTER FUNCTION IntegerToDatetime (@int INT)
RETURNS DATETIME
AS
BEGIN
DECLARE @IntegerToDatetime int
DECLARE @time DATETIME
SET @time = '2001-01-01'
SET @IntegerToDatetime =
CASE
WHEN LEN(@int) = 7
THEN '20' + CAST(SUBSTRING(CAST(@int AS CHAR(7)),2,2) AS int)
+ '-' + CAST(SUBSTRING(CAST(@int AS CHAR(7)),4,2) AS int)
+ '-' + CAST(SUBSTRING(CAST(@int AS CHAR(7)),6,2) AS int)
WHEN LEN(@int) = 6
THEN '19' + CAST(SUBSTRING(CAST(@int AS CHAR(6)),1,2) AS int)
+ '-' + CAST(SUBSTRING(CAST(@int AS CHAR(6)),3,2) AS int)
+ '-' + CAST(SUBSTRING(CAST(@int AS CHAR(6)),5,2) AS int)
WHEN LEN(@int) = 5
THEN '200' + CAST(SUBSTRING(CAST(@int AS CHAR(5)),1,1) AS int)
+ '-' + CAST(SUBSTRING(CAST(@int AS CHAR(5)),2,2) AS int)
+ '-' + CAST(SUBSTRING(CAST(@int AS CHAR(5)),4,2) AS int)
WHEN LEN(@int) = 4 THEN cast(@time AS INT)

END
RETURN (@IntegerToDatetime )
END

GO


INPUT
-------------------------------
990831
981019

RESULT
-------------------------------
1900-01-02 00:00:00.000
1900-05-27 00:00:00.000




http://www.sqlserverstudy.com

View 17 Replies View Related

Integer To Datetime

Apr 18, 2008

Hi

I use this to get all users from active directory.


SELECT *

FROM openquery(

adsi

,'SELECT name, AccountExpires FROM

''LDAP://company/OU=users,dc=company,dc=com''')

WHERE AccountExpires IS NOT NULL AND AccountExpires not in('0','0x7FFFFFFFFFFFFFFF','9223372036854775807','')

AccountExpires returns values like 128514708000000000 (This value represents the number of 100 nanosecond intervals since January 1, 1601 )

How do I convert this value to Datetime?


select getdate() returns a value like 2008-04-18 10:00:00.00 and that's how I'd like my AccountExpires

View 11 Replies View Related

Datetime To Integer

Apr 30, 2007

I was just told that it is better to convert all datetime values to integers for performance reasons. Is this generally true? I am working with time series data so datetime values hold important information.

View 10 Replies View Related

Can't Convert Record To Integer

Jan 11, 2007

Hi All
I'm getting an error that says that this can't be converted to an integer.
Here is the line that gets the error. dt = ((DataView)(EventDataSource1.Select(dssa))).ToTable()
I have also tried.  dt = (DataView)(EventDataSource1.Select(dssa);
I am programming in VB
here is teh rest of my code.
Dim EventDataSource1 As New SqlDataSource()EventDataSource1.ConnectionString = ConfigurationManager.ConnectionStrings("ASPNETDBConnectionString").ToStringDim dssa As New DataSourceSelectArguments()Dim EventID As String = ""Dim DataView = ""Dim dt As New Data.DataTableDim conn As New Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("ASPNETDBConnectionString").ToString())Dim cmd As New Data.SqlClient.SqlCommand("SELECT EventID FROM Event WHERE ([StartDate] = @StartDate)", conn)EventDataSource1.SelectCommand = ("SELECT EventID FROM Event WHERE ([StartDate] = @StartDate)")conn.Open()dt = ((DataView)(EventDataSource1.Select(dssa))).ToTable()EventID = dt.Rows(0)(0).ToString()EventDataSource1.SelectParameters.Add("@StartDate",StartDate)EventID = cmd.ExecuteScalar()

View 4 Replies View Related

Convert Returned Value To Integer

Apr 3, 2006

I have the following stored procedure for creating a transaction record and after inserting the record, the transaction id is returned.-----------------------------------------------------DECLARE @TransactionID int    <------ INSERT statement (after inserting the record, select the identity ID) --------->        Select @TransactionID = @@Identity    RETURN------------------------------------------------------...Dim transactionID As Integerconnection.Open()Dim reader As SqlDataReaderreader = command.ExecuteReader(CommandBehavior.CloseConnection)Dim p3 As New SqlParameter("@TransactionID", SqlDbType.Int)p3.Direction = ParameterDirection.OutputtransactionID = Convert.ToInt16(p3.Value)connection.Close()...I wanna retrieve the transactionID of the newly inserted record so that I can use it in my next step of inserting a new record to another table which has reference to the transactionID as a foreign key. However, I encountered error and suspect that it is due to the conversion of the output to Integer as it worked when I tested using dummy Integers.I tried many different ways of conversion but couldn't resolve the error. Could anyone help?

View 3 Replies View Related

How To Convert A Hex String To An Integer?

Feb 1, 2000

Hi folks,
I'm trying to import data from a text file (UnicodeData.txt) into
an SQL table. Some of the fields are unicode values (16 bits)
expressed as four hexidecimal digits. I've succeeded in importing
the data as character strings, but I have not found a way to convert
them into numbers. (They could be stored as int or nchar.)
I've tried convert(binary/int/whatever, string); E.g.
select convert(int, '0x1111') from import_unicode
gives the error
Syntax error converting the varchar value '0x1111' to a column of data type int.

I could write code to strip off one character at a time, convert the
hex digit to a decimal value, shift left, etc., but I find it hard
to believe that's the best way.

Any help is appreciated. Please email answer to lars_huttar@sil.org
as I don't read this board.

Thanks,
Lars Huttar
lars_huttar@sil.org

View 3 Replies View Related

How Can I Convert Varchar Value To Integer

Mar 13, 2002

hi i want to insert the varchar value inter column, how can i convert the values and insert in to the record if i give direct column name i am getting a message
insert into EMP(id)
SELECT name from STU

i am getting a message like this
Syntax error converting the varchar value '200.00' to a column of data type int.

View 3 Replies View Related

How To Convert Date To Integer?

Mar 27, 2008



Hi,

I have checked the forums but couldnt find exact term.
I have written tsql statement but I dont know how to use that in SSIS
this is a update statement in oledb command component...
I wanna get integer like YYYYMMDD ( 20080325)

UPDATE [dbo].[d_cust] SET [per_xxx] = ? ,
[per_valid]=(select cast(CONVERT(varchar ,DATEADD(dd,-1,getdate()),112 )as int))


View 3 Replies View Related

Converting Integer To Datetime

Jul 20, 2005

Hi All,How do you convert int value to datetime datatype in sql servere.g 900mins to hh:mm:ssRegardsOla*** Sent via Developersdex http://www.developersdex.com ***Don't just participate in USENET...get rewarded for it!

View 3 Replies View Related

Convert Char Into Integer For DB2 In DTS Package?

Mar 26, 2004

Hi,
I am extracting data from DB2 into SQL server using DTS. We have the data type char(5) in DB2 and int in SQL server.
I tried to give the
select integer(columname) as columname from tablename in data source.
I did parse the query it was Ok but If I tried to execute that giving the following error.
Can you give me your answere for this issue.


---------------------------
Package Error
---------------------------
Error Source : Microsoft OLE DB Provider for ODBC Drivers

Error Description : [StarQuest][StarSQL ODBC Driver][DB2]THE VALUE OF A CHARACTER STRING ARGUMENT WAS NOT ACCEPTABLE TO THE INTEGER FUNCTION

---------------------------
OK
---------------------------

View 4 Replies View Related

Convert Day Of Week Integer To Weekday Name?

Sep 10, 2007

In a table, I store an integer to represent a day of the week (1 = sunday ) and then in procedures, compare that to datepart(dw, getdate()) to do alternative tasks on certain days.

If I have the number 1, is there a built in function to convert that to sunday or should one just write a function to do just that?

View 3 Replies View Related

How Can I Convert Binary(16) To Integer Or Numeric?

Feb 16, 2006

HI!!!:shocked:

Im trying to convert 0x00085180F0A2D511B69600508BE96424 to Integer or numeric format.

I just tried, At to many forms and combinations of that query
Help me !!!

SELECT CAST(CAST(CAST("field name " AS nvarchar) AS varbinary) AS float)

select cast(cast("field name " as varbinary)as integer)

select convert(int," field name") from FILE

select convert(varchar," field name") from FILE



The only answer that I have is
-1947638748 or ‘ ‘ or

And if I try with to many rows of the field at the same format,
It Answer me the same: -1947638748 for all the rows.

Thank`s for all

View 5 Replies View Related

How To Convert Varchar Type To Integer

Sep 19, 2014

SQL command ....

declare @found int;
set @found = 'select sid from StickyContent where StickyId='+0+' and UserId='+171
exec (@found)
delete from StickyContent where sid = @found

I need to pass this statement from my UI i.e in a single query. I am getting this error.

"Conversion failed when converting the varchar value 'select sid from StickyContent where StickyId=' to data type int.
"

View 2 Replies View Related

How Do I Convert A String To An Integer For A Parameter?

Dec 14, 2006

I want to convert a string into an interger so that my parameter can get one value, and have a seperate matrix list the value before the value selected.

My parameter is year. The user picks the year. And i want the crashcounts for the year displayed in the matrix. Then i have another matrix with a dataset similiar. I want this seperate Matrix/Dataset to display the previous year.

SO if the user selects 2004 from the dropdown. 2004 is displayed in the first matrix, and 2003 is displayed in the second matrix. The year attribute is in string format, and i cant change it in the cube. So i was told it could be converted in reporting services. with this



=CStr(CInt(Parameters!CrashStatisticalYear.Value)-1)



Question is, where do i put this...and how come when i put it in the parameters expression for the 2nd matrix, i get an error datatype messege? HELP !

View 2 Replies View Related

Convert Nvarchar Values To Integer

Mar 13, 2007

I have imported a text file with various data into sql table. all these values have been imported as nvarchar. I need to convert these into Integer. the format of the values is 10length i.e. 0000000.00.
example of data:
0001028.99 - needs to be shown as 1028.99
222.00 - needs to be shown as 222.00
0000190.89 - needs to be shown as 190.89
2708.99 - needs to be shown as 2708.99
00000-50.99 - needs to be shown as -50.99
-109.79 - needs to be shown as -109.70

as you can see some of the values have leading zeros and some don't.
i have tried converting from nvarchar to int and i get the error cannot convert nvarchar to int, i believe it may be because the data contains negative values as well as positive values.

Is there a split function or position function which i can use to extract the data? or any other methods which i can use would be really helpful.

Thanks

View 4 Replies View Related

Converting Integer To Datetime Format

May 2, 2006

Hello Everyone,

I need help with conversion type. I'm using Visual Basic 6.0 as my frontend and SQL Server 2000 as my backend. There has been existing data in the database. I would like to know how to convert an integer to datetime format. For example:

This is the actual value from the database.

1087912290
1087912327

I'd like to know how to convert it datetime format.

Any help would be greatly appreciated.

Thanks,

Dennis

View 14 Replies View Related

Converting Datetime To Integer And Back

Jul 20, 2005

Hi all,I have a problem converting datetime to integer (and than back todatetime).Depending whether the time is AM or PM, same date is converted to twodifferent integer representations, which holds as true on reversalback to datetime.AM Example:declare @DI integer; declare @DD datetimeset @DI = cast(cast('3/12/2003 11:34:02 AM' as datetime) as integer)set @DD = cast (@DI as datetime)print @DI; print @DDResult:37690Mar 12 2003 12:00AMPM Example:declare @DI integer; declare @DD datetimeset @DI = cast(cast('3/12/2003 11:34:02 PM' as datetime) as integer)set @DD = cast (@DI as datetime)print @DI; print @DDResult:37691Mar 13 2003 12:00AMNow, this is not a big problem if I knew that this is how it issupposed to work. Is this how SQL Server is supposed to work?

View 3 Replies View Related

Convert Datetime String To Datetime Date Type

Mar 11, 2014

I am inserting date and time data into a SQL Server 2012 Express table from an application. The application is providing the date and time as a string data type. Is there a TSQL way to convert the date and time string to an SQL datetime date type? I want to do the conversion, because SQL displays an error due to the

My date and time string from the application looks like : 3/11/2014 12:57:57 PM

View 1 Replies View Related

SQL Server 2012 :: Convert Integer To Date

Oct 16, 2014

In VBA, CLng(Now) will return the integer portion of a date CLng(Now) returns 41928, CDate(41928) then returns 10/16/2014. Is there something equivalent in SQL Server that will allow me to convert an integer value to a date?

In short, how can I convert a 100 year date to Gregorian (any format)?

View 3 Replies View Related

SQL Server 2012 :: Convert Integer To Time?

Dec 3, 2014

I've got a column that holds a time value in Integer form as a number from midnight (IE military time) with no leading 0s or colons.

0 = 00:00
30 = 00:30
...

1700 = 1700 etc...

How can I convert this to a real time field?

View 9 Replies View Related

Convert Column Of Data Alphanumeric To Integer

Nov 14, 2013

I need to convert a column of data from alpha numeric to integer.

I am only querying the tables i.e. i don't have access to actually change the data tables themselves.

CAST or CONVERT throws up an error. Are there any other commands i can use at the query stage?

The data I need to convert is always actually a number. i.e. even though it is recognised as alpha numeric, the figure is a number.

I just need it to be converted to an integer so i can SUM it etc.

View 8 Replies View Related

T-SQL Script To Convert An Integer Into Years And Months

Dec 15, 2007



Hi there,

for displaying purposes I'm trying to convert number of months into years and months. ie. 35 months = 2 years and 11 months.

how can I do this within a T-SQL script?

Thanks for your help.

Manny

View 1 Replies View Related

Query DB2 From SSRS And Convert Integer To Time

Aug 8, 2007

Hi,

I am querying DB2 from SSRS. I get an interger back that represents a time like this: HHMMSS
(The data type in DB2 is an integer.) I would like to make this representation of the time display a little more friendly. Does anyone have a good idea on how I can change the query or SSRS format to display semi-colons to break up the hours, minutes and seconds? Also, the other issue is that since I don't get leading zeros back....they probably need to be added to this value if the value is not a full 6 characters.

View 3 Replies View Related

Random Integer, Sample, And Datetime Functions

Jul 23, 2006

Edit: There seems to be some interaction between GROUP BY/NEWID() that can cause problems if these functions are used directly in an aggregate query. Please read the posts on this thread about this, and use caution.


This script creates three functions, F_RANDOM_INTEGER, F_RANDOM_SAMPLE, and F_RANDOM_DATETIME. The last parameter of each function must be function NEWID() to generate the random number.

Theses functions are designed for applications where it is necessary to generate random integers, random datetimes, or take random samples from sets of data. Typical applications would be software testing, inventory control, auditing, and product quality testing.

Function F_RANDOM_INTEGER returns a random integer in the range of the input parameters so that the return value is >= @START_INT and <= @END_INT. It is valid for any range of two integer values.

Function F_RANDOM_SAMPLE returns a 1 or a 0 to determine if a sample should be selected, based on the input sample rate. Input parameter @SAMPLE_RATE should be between 1 and 999,999. The sample rate determines how many samples should be selected out of each 1,000,000 samples. A sample rate below 1 will never select a sample, and a sample rate above 999,999 will always select a sample. A sample rate of 1,000 = 0.1%, 50,000 = 5%, 63,775 = 6.3775%, 100,000 = 10%, and 500,000 = 50%.

F_RANDOM_DATETIME returns a random datetime value >= @START_TIME and < @END_TIME. It is valid for any datetime range. Input parameters default, if null, to @START_TIME = '19000101' and @END_TIME = '19000102’. The datetime is random to the level of clock ticks (1/300 of as second). Note that the latest time is not included in the range of datatime values that can be returned. This is to allow selection of times within adjacent time periods, without having to specify times to the level of milliseconds. This means a range of 1990-12-01 01:00:00.000 through 1990-12-01 02:00:00.000 will never return a value of 1990-12-01 02:00:00.000.

The NEWID() function is the basis of the random numbers. These functions should not to be considered random for purposes of data encryption or other high security applications. However, they should be adequate for business applications of the types mentioned above. I conducted extensive testing with the functions where I generated millions of results, analyzed the results various ways to look for non-random patterns, and I saw no evidence of non-random results.

The script also includes a demo of each function, and sample output from the demos is also included.

The demo script uses the number table function, F_TABLE_NUMBER_RANGE, available on this link:
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=47685





if objectproperty(object_id('dbo.F_RANDOM_INTEGER'),'IsScalarFunction') = 1
begin drop function dbo.F_RANDOM_INTEGER end
go
create function dbo.F_RANDOM_INTEGER
(
@START_INTint,
@END_INTint,
@NEWIDuniqueidentifier
)
returns
int
as
/*
Function: F_RANDOM_INTEGER

This function returns a random integer
value >= @START_INT and <= @END_INT.

Valid for any integer range.

Requires newid() to be input parameter @NEWID
to generate the random number.

-- Return random integer between -100, 200000
select [Random Integer] =
[dbo].[F_RANDOM_INTEGER](-100, 200000,newid())
*/
begin

declare @sn bigint
declare @en bigint
declare @mod bigint
declare @rand_bigint bigint
declare @rand_result int

-- Set default values for input dates if they are null
if @START_INT is null begin set @START_INT = 0 end
if @END_INT is null begin set @END_INT =1000000 end

-- Set order of input parameters so that return value is always
-- the same no matter what order the input values are passed.
if @START_INT > @END_INT
select @sn = @END_INT, @en = @START_INT
else
select @sn = @START_INT, @en = @END_INT

-- Return start int if start int = end int
if @sn = @en return @sn

-- Get modulus
select @mod = @en-@sn+1

-- Get random bigint from input parameter @NEWID
select @rand_bigint = abs(convert(bigint,convert(varbinary(20),@NEWID)))


-- Get random integer
select @rand_result = @sn+(@rand_bigint%@mod)

return @rand_result

end
go
grant execute on dbo.F_RANDOM_INTEGER to public
go

if objectproperty(object_id('dbo.F_RANDOM_SAMPLE'),'IsScalarFunction') = 1
begin drop function dbo.F_RANDOM_SAMPLE end
go
create function dbo.F_RANDOM_SAMPLE
(
@SAMPLE_RATEint,
@NEWIDuniqueidentifier
)
returns
int
as
/*
Function: F_RANDOM_SAMPLE

This function returns a 1 or a 0 to determine if a sample
should be selected, based on the sample rate. It is designed
to select random samples at a specific rate.

Input parameter @SAMPLE_RATE should be between 1 and 999,999.
The sample rate determines how many samples should be
selected out of each 1,000,000 samples. A sample rate below 1
will never select a sample, and a sample rate above 999,999 will
always select a sample. 1,000 = 0.1%, 50,000 = 5%, 63,775 = 6.3775%,
100,000 = 10%, and 500,000 = 50%

Requires newid() to be input parameter @NEWID
to generate the random number.

-- Select sample 200,000 times in 1,000,000 samples (20%)
select [Random Sample] =
[dbo].[F_RANDOM_SAMPLE](200000,newid())
*/
begin

declare @rand_bigint bigint

-- Get random bigint from @NEWID
select @rand_bigint = abs(convert(bigint,convert(varbinary(20),@NEWID)))


-- Select sample if the modulus of @rand_bigint is less than the sample rate
return case when @rand_bigint%1000000 < @SAMPLE_RATE then 1 else 0 end

end
go
grant execute on dbo.F_RANDOM_SAMPLE to public
go

if objectproperty(object_id('dbo.F_RANDOM_DATETIME'),'IsScalarFunction') = 1
begin drop function dbo.F_RANDOM_DATETIME end
go
create function dbo.F_RANDOM_DATETIME
(
@START_TIMEdatetime,
@END_TIMEdatetime,
@NEWIDuniqueidentifier
)
returns
datetime
as
/*
Function: F_RANDOM_DATETIME

This function returns a random datetime
value >= @START_TIME and < @END_TIME.

Valid for any datetime range.

Input parameters default, if null, to:
@START_TIME'19000101'
@END_TIME'19000102'

Requires newid() to be input parameter @NEWID
to generate the random number.

-- Return random time between 08:30 and 12:00
select [Random Time] =
[dbo].[F_RANDOM_DATETIME]('08:30:00.000','12:00:00.000',newid())
*/
begin

declare @st datetime
declare @et datetime

declare @hours int
declare @ms int
declare @ticks bigint
declare @rand_ticks bigint
declare @rand_bigint bigint

declare @remaining_ticks int
declare @return_hours int
declare @return_ms int

-- Set default values for input dates if they are null
if @START_TIME is null begin set @START_TIME = '19000101' end
if @END_TIME is null begin set @END_TIME = '19000102' end

-- Set order of input parameters so that return value is always
-- the same no matter what order the input values are passed.
if @START_TIME > @END_TIME
select @st = @END_TIME, @et = @START_TIME
else
select @st = @START_TIME, @et = @END_TIME

-- Return start time if start time = end time
if @st = @et return @st

-- Get hours boundary difference.
-- Subtract 1 from diff, before dividing by 2 and multiplying by 2
-- so the milliseconds remaining is always positive and
-- hours is always >= zero.
set @hours = ((datediff(hh,@st,@et)-1)/2)*2

-- Get remainder milliseconds
set @ms = datediff(ms,0,@et-dateadd(hh,@hours,@st))

-- Convert remainder milliseconds to
-- SQL Server 'clock ticks' of 1/300 of a second
set @ticks = ((@ms/10)*3) + ((@ms%10)/3)

-- Add hours * tick per hour (3600*300) to give total
-- ticks between @START_TIME and @END_TIME
set @ticks = @ticks + (@hours * 0000001080000 )

-- Get random bigint from input parameter @NEWID
select @rand_bigint = abs(convert(bigint,convert(varbinary(20),@NEWID)))

-- Get random number of ticks
select @rand_ticks = @rand_bigint%@ticks

-- Get hours component of random ticks
select @return_hours = @rand_ticks/1080000

-- Get left over ticks after removing hours.
select @remaining_ticks = @rand_ticks%1080000

--Convert remaining clock ticks back to milliseconds
select @return_ms = ((@remaining_ticks/3)*10) + floor(((@remaining_ticks%3)*3.5))

-- Return the random time between the start and end time
return dateadd(ms,@return_ms,dateadd(hh,@return_hours,@st))

end
go
grant execute on dbo.F_RANDOM_DATETIME to public
go

print '-----------------------------------------------------------------'
print ' Demo F_RANDOM_INTEGER function'
print '-----------------------------------------------------------------'
print ''

declare @t table ([Random Integer] int not null )

insert into @t
select
-- Get integert in range of 1 to 10,000,000
[Random Integer] =
[dbo].[F_RANDOM_INTEGER](1,10000000,newid() )
from
-- Function F_TABLE_NUMBER_RANGE
-- available in Script Library forum
F_TABLE_NUMBER_RANGE(1,100000)


select
[Right Int] = [Random Integer]%10,
[Count] = count(*)
from
@t a
group by
[Random Integer]%10
order by
1,2

select
[Million Range] = [Random Integer]/1000000,
[Count] = count(*)
from
@t a
group by
[Random Integer]/1000000
order by
1,2

go
print '-----------------------------------------------------------------'
print ' Demo F_RANDOM_SAMPLE function'
print '-----------------------------------------------------------------'
print ''

declare @t table ([Sample Taken] int not null )

insert into @t
select
-- Sample rate = 6.3775%
[Sample Taken] = [dbo].[F_RANDOM_SAMPLE](63775,newid())
from
-- Function F_TABLE_NUMBER_RANGE
-- available in Script Library forum
F_TABLE_NUMBER_RANGE(1,100000)

select
[Sample Taken],
[Result Count] = count(*)
from
@t a
group by
[Sample Taken]
order by
1,2


go

print '-----------------------------------------------------------------'
print ' Demo F_RANDOM_DATETIME function'
print '-----------------------------------------------------------------'
print ''
select
Random_Datetime =
convert(varchar(23),[dbo].[F_RANDOM_DATETIME]( a.ST, a.ET,newid() ) ,121) ,
[Start] = convert(varchar(23),a.ST ,121) ,
[End] = convert(varchar(23),a.ET ,121) ,
a.Comment
from
(
select ST = getdate(), ET = getdate()+2 ,
Comment = 'Now thru 2 days from now' union all
select '20060101', '20060102' , 'One day diff' union all
select '20030101', '20030101' ,'Both times same' union all
select '20030101', '20030108' ,'One week diff' union all
select '20021228', '20030104' ,'One week diff' union all
select '20010701', '20010713' ,'12 day diff' union all
select '20010701', '20010714' ,'13 day diff' union all
select '20010630', '20010713' ,'13 day diff' union all
select '19901201 01:00:00.000', '19901201 02:00:00.000' ,'1 hour diff' union all
select '19901201 01:00:33.003', '19901201 02:00:33.003' ,'1 hour diff' union all
select '19901201 01:00:00.000', '19901201 01:30:00.000' ,'30 min diff' union all
select '19901201 01:00:33.447', '19901201 01:30:33.447' ,'30 min diff' union all
select '19901201 01:00:00.000', '19901201 01:05:00.000' ,'5 min diff' union all
select '19901201 01:00:29.123', '19901201 01:05:29.123' ,'5 min diff' union all
select '19901201 01:00:00.000', '19901201 01:01:00.000' ,'1 min diff' union all
select '19901201 01:00:00.000', '19901201 01:00:01.000' ,'1 sec diff' union all
select '19901201 01:00:00.000', '19901201 01:00:00.100' ,'100 ms diff' union all
select '19901201 01:00:00.000', '19901201 01:00:00.050' ,'50 ms diff' union all
select '19901201 01:00:00.000', '19901201 01:00:00.023' ,'23 ms diff' union all
select '19901201 01:00:00.000', '19901201 01:00:00.020' ,'20 ms diff' union all
select '19901201 01:00:00.000', '19901201 01:00:00.013' ,'13 ms diff' union all
select '19901201 01:00:00.000', '19901201 01:00:00.010' ,'10 ms diff' union all
select '19901201 01:00:00.000', '19901201 01:00:00.007' ,'7 ms diff' union all
select '19901201 01:00:00.000', '19901201 01:00:00.003' ,'3 ms diff' union all
select '20030101', '20030201' ,'One month diff 31 days' union all
select '20030101', '20040101' ,'One year diff' union all
select '20050101', '20070101' ,'Two year diff' union all
select '20060101', '20060301' ,'2 month diff' union all
select null, '20060101' ,'Start time null' union all
select '20060102', null ,'End time null' union all
select null, null ,'Both null' union all
select '17530101', '99991231 23:59:59.997' ,'Max datetime diff' union all
select '99991231 23:59:59.997','17530101' ,'Max datetime diff reversed'
) a


Demo Results:


-----------------------------------------------------------------
Demo F_RANDOM_INTEGER function
-----------------------------------------------------------------


(100000 row(s) affected)

Right Int Count
----------- -----------
0 9929
1 10055
2 10009
3 10082
4 9919
5 10022
6 9914
7 9985
8 10098
9 9987

(10 row(s) affected)

Million Range Count
------------- -----------
0 10009
1 9985
2 10142
3 10047
4 9967
5 9907
6 10078
7 10071
8 9790
9 10004

(10 row(s) affected)

-----------------------------------------------------------------
Demo F_RANDOM_SAMPLE function
-----------------------------------------------------------------


(100000 row(s) affected)

Sample Taken Result Count
------------ ------------
0 93669
1 6331

(2 row(s) affected)

-----------------------------------------------------------------
Demo F_RANDOM_DATETIME function
-----------------------------------------------------------------

Random_Datetime Start End Comment
----------------------- ----------------------- ----------------------- --------------------------
2006-07-24 08:21:22.593 2006-07-23 17:54:47.283 2006-07-25 17:54:47.283 Now thru 2 days from now
2006-01-01 06:44:36.897 2006-01-01 00:00:00.000 2006-01-02 00:00:00.000 One day diff
2003-01-01 00:00:00.000 2003-01-01 00:00:00.000 2003-01-01 00:00:00.000 Both times same
2003-01-05 01:57:02.183 2003-01-01 00:00:00.000 2003-01-08 00:00:00.000 One week diff
2003-01-01 20:02:05.550 2002-12-28 00:00:00.000 2003-01-04 00:00:00.000 One week diff
2001-07-02 11:35:11.147 2001-07-01 00:00:00.000 2001-07-13 00:00:00.000 12 day diff
2001-07-02 16:39:57.433 2001-07-01 00:00:00.000 2001-07-14 00:00:00.000 13 day diff
2001-07-06 12:33:53.087 2001-06-30 00:00:00.000 2001-07-13 00:00:00.000 13 day diff
1990-12-01 01:15:42.530 1990-12-01 01:00:00.000 1990-12-01 02:00:00.000 1 hour diff
1990-12-01 01:02:21.647 1990-12-01 01:00:33.003 1990-12-01 02:00:33.003 1 hour diff
1990-12-01 01:21:06.267 1990-12-01 01:00:00.000 1990-12-01 01:30:00.000 30 min diff
1990-12-01 01:26:17.983 1990-12-01 01:00:33.447 1990-12-01 01:30:33.447 30 min diff
1990-12-01 01:00:56.327 1990-12-01 01:00:00.000 1990-12-01 01:05:00.000 5 min diff
1990-12-01 01:03:20.423 1990-12-01 01:00:29.123 1990-12-01 01:05:29.123 5 min diff
1990-12-01 01:00:21.617 1990-12-01 01:00:00.000 1990-12-01 01:01:00.000 1 min diff
1990-12-01 01:00:00.443 1990-12-01 01:00:00.000 1990-12-01 01:00:01.000 1 sec diff
1990-12-01 01:00:00.050 1990-12-01 01:00:00.000 1990-12-01 01:00:00.100 100 ms diff
1990-12-01 01:00:00.000 1990-12-01 01:00:00.000 1990-12-01 01:00:00.050 50 ms diff
1990-12-01 01:00:00.010 1990-12-01 01:00:00.000 1990-12-01 01:00:00.023 23 ms diff
1990-12-01 01:00:00.017 1990-12-01 01:00:00.000 1990-12-01 01:00:00.020 20 ms diff
1990-12-01 01:00:00.007 1990-12-01 01:00:00.000 1990-12-01 01:00:00.013 13 ms diff
1990-12-01 01:00:00.000 1990-12-01 01:00:00.000 1990-12-01 01:00:00.010 10 ms diff
1990-12-01 01:00:00.003 1990-12-01 01:00:00.000 1990-12-01 01:00:00.007 7 ms diff
1990-12-01 01:00:00.000 1990-12-01 01:00:00.000 1990-12-01 01:00:00.003 3 ms diff
2003-01-14 09:00:09.520 2003-01-01 00:00:00.000 2003-02-01 00:00:00.000 One month diff 31 days
2003-08-27 11:47:04.100 2003-01-01 00:00:00.000 2004-01-01 00:00:00.000 One year diff
2006-11-23 03:57:21.737 2005-01-01 00:00:00.000 2007-01-01 00:00:00.000 Two year diff
2006-01-12 08:50:40.717 2006-01-01 00:00:00.000 2006-03-01 00:00:00.000 2 month diff
1933-11-15 13:39:10.050 NULL 2006-01-01 00:00:00.000 Start time null
1997-05-28 06:42:32.407 2006-01-02 00:00:00.000 NULL End time null
1900-01-01 01:50:42.743 NULL NULL Both null
2758-10-18 13:50:47.987 1753-01-01 00:00:00.000 9999-12-31 23:59:59.997 Max datetime diff
8426-03-24 13:51:08.407 9999-12-31 23:59:59.997 1753-01-01 00:00:00.000 Max datetime diff reversed

(33 row(s) affected)





CODO ERGO SUM

View 6 Replies View Related

Need Query To Select VarChar Rows That Can Convert To Integer

Jul 23, 2005

I have a table of zip codes, some with Canadian zips. I'd like to takea zip code and search for nearby zips. For example:Dim theZip As Integer = textbox1.text....Parameter.Add(@ziplow, SqlDbType.Int, 5).Value = (theZip - 10)....Parameter.Add(@ziphigh, SqlDbType.Int, 5).Value = (theZip + 10)SELECT * from ZIPCODES where Cast(zip_code as Integer) BETWEEN @lowzipAND @highzipProblem is the letters in the Canadian records cannot be cast asintegers for this process. I get this error:Syntax error converting the varchar value '53151 1' to a column of datatype int.Is there a SQL query that can exclude if no cast can be made to anInteger?Thanks!Anton

View 5 Replies View Related

How To Convert Datetime From Text/char To Datetime

Jul 20, 2005

Hi,I have a text file that contains a date column. The text file will beimported to database in SQL 2000 server. After to be imported, I wantto convert the date column to date type.For ex. the text file look likeName dateSmith 20003112Jennifer 19991506It would be converted date column to ydm database in SQL 2000 server.In the table it should look like thisName DateSmith 2000.31.12Jennifer 1999.15.06Thanks in advance- Loi -

View 1 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved