converting hours to seconds in sql query - sql-server-2008

Hi is there any simple way to convert hours to seconds? by using sql query.
Ex: #mytime = 2:15 hours
expected output is #result = 8100 seconds.
2 * 3600 + 15 * 60 = 8100
Thanks

You already presented the simplest way 8-)
If you want to convert hour string, then:
DECLARE #str VARCHAR(10) = '5:35'
SELECT
CAST(SUBSTRING(#str, 1, CHARINDEX(':', #str, 1)-1) AS INT)*3600+
CAST(SUBSTRING(#str, CHARINDEX(':', #str, 1)+1, 1000) AS INT)*60

There is a simpler way that works in SQL server and is less error prone.
DECLARE #str CHAR(5) = '02:15'
SELECT
DATEDIFF(SECOND, '00:00', #str)

Related

insert in table with between?

Im trying to make a table with zip codes and states for Norway and since its in order I want to bulk insert instead of inserting one and one. so from 0000 to 1295 is Oslo so I tried this but is failing anyone have some solution?
insert into poststed (postnr, poststed) values
(between 0000 and 1295, 'Oslo'),
(between 1300 and 1304, 'Sandvika');
I dont know if using this type of between is supported in SQL. but I see a huge duplication in your data model. Better You think about changing it.
Your data model could look like
Start , End , poststed
0000 , 1295 , oslo
This way, you will be done within two rows, and have them indexed, if you want.. and your query can go like
SELECT poststed FROM MYTABLE WHERE :value between MYTABLE.START AND MYTABLE.END
Something similar to this should work. Please refer to this question for more query details - Select BETWEEN column values
Hope this helps!
Why not use a for loop? You havent specified which version of SQL you are using, let me know and I will find the right syntax, but here is roughly what you need
https://www.techonthenet.com/sql_server/loops/for_loop.php
Generate automatic data without between:
-- step 1
declare #start int = 0
declare #end int = 1295
;with numcte
AS
(
SELECT #start [SEQUENCE]
UNION all
SELECT [SEQUENCE] + 1
FROM
numcte WHERE [SEQUENCE] < #end
)
INSERT into poststed (postnr, poststed)
SELECT *,'Oslo' FROM numcte option (maxrecursion 0)
--step 2
declare #start2 int = 1300
declare #end2 int =1304
;with numcte
AS
(
SELECT #start2 [SEQUENCE]
UNION all
SELECT [SEQUENCE] + 1
FROM
numcte WHERE [SEQUENCE] < #end2
)
INSERT into poststed (postnr, poststed)
SELECT *,'Sandvika' FROM numcte option (maxrecursion 0)

How to convert int to date in MS Sql

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.

COALESCE truncating concatenation output

In a recent post Sql server rtrim not working for me, suggestions?, I got some good help getting a csv string out of a select query. It's behaving unexpectedly though, and I can't find any similar examples or documentation on it. The query returns 802 records without the coalesce statement, as a normal select. With the coalesce, I'm getting back just 81. I get this same result if I output to text, or output to file. This query returns 800+ rows:
declare #maxDate date = (select MAX(TradeDate) from tblDailyPricingAndVol)
select p.Symbol, ','
from tblDailyPricingAndVol p
where p.Volume > 1000000 and p.Clse <= 40 and p.TradeDate = #maxDate
order by p.Symbol
But when I attempt to concatenate those values, many are missing:
declare #maxDate date = (select MAX(TradeDate) from tblDailyPricingAndVol)
declare #str VARCHAR(MAX)
SELECT #str = COALESCE(#str+',' ,'') + LTRIM(RTRIM((p.Symbol)))
FROM tblDailyPricingAndVol p
WHERE p.Volume > 1000000 and p.Clse <= 40 and p.TradeDate = #maxDate
ORDER by p.Symbol
SELECT #str
This should be working fine, however here is how I would do it:
DECLARE #str VARCHAR(MAX) = '';
SELECT #str += ',' + LTRIM(RTRIM(Symbol))
FROM dbo.tblDailyPricingAndVol
WHERE Volume > 1000000 AND Clse <= 40 AND radeDate = #maxDate
ORDER by Symbol;
SET #str = STUFF(#str, 1, 1, '');
To determine whether the string is complete, stop looking at the output in Management Studio. This is always going to be truncated if you exceed the number of characters Management Studio will show. You can run a couple of tests to check the variable without inspecting it in its entirety:
A. Compare the datalength of the individual parts to the datalength of the result.
SELECT SUM(DATALENGTH(LTRIM(RTRIM(Symbol)))) FROM dbo.tblDailyPricingAndVol
WHERE ...
-- concatenation query here
SELECT DATALENGTH(#str);
-- these should be equal or off by one.
B. Compare the end of the variable to the last element in the set.
SELECT TOP 1 Symbol FROM dbo.tblDailyPricingAndVol
WHERE ...
ORDER BY Symbol DESC;
-- concatenation query here
SELECT RIGHT(#str, 20);
-- is the last element in the set represented at the end of the string?

Mysql insert random datetime in a given datetime range

With SQL , Can I insert random datetime values in a column giving a range?
For example, given a range of 2010-04-30 14:53:27 to 2012-04-30 14:53:27
I'm getting confused with the range part. as i will have just done this
INSERT INTO `sometable` VALUES (RND (DATETIME()))
Here is an example that should help:
INSERT INTO `sometable` VALUES(
FROM_UNIXTIME(
UNIX_TIMESTAMP('2010-04-30 14:53:27') + FLOOR(0 + (RAND() * 63072000))
)
)
It uses the date 2010-04-30 14:53:27 as the base, converts that to a Unix timestamp, and adds a random number of seconds from 0 to +2 years to the base date and converts it back to a DATETIME.
It should be pretty close but over longer time periods leap years and other adjustments will throw it off.
This should work nicely:
SET #MIN = '2010-04-30 14:53:27';
SET #MAX = '2012-04-30 14:53:27';
SELECT TIMESTAMPADD(SECOND, FLOOR(RAND() * TIMESTAMPDIFF(SECOND, #MIN, #MAX)), #MIN);
TIMESTAMPDIFF is used to determine the number of seconds in the date range. Multiply this by a random number between 0-1 results in a random number between 0 and the number of seconds in the range. Adding this random number of seconds to the lower bound of the range results in a random date between the data range bounds.
This works perfectly even for leap years:
select from_unixtime(
unix_timestamp('2000-1-1') + floor(
rand() * (
unix_timestamp('2010-12-31') - unix_timestamp('2000-1-1') + 1
)
)
)
The idea is simple: Just take a random timestamp between the two timestamps, then convert it to a datetime using from_unixtime. This way you can ensure that each option has equal probability.
Easiest way out:
INSERT INTO `sometable` VALUES (SELECT timestamp('2010-04-30 14:53:27') - INTERVAL FLOOR( RAND( ) * 366) DAY);
Just try :
SELECT TIMESTAMP('2012-04-30 14:53:27')-INTERVAL RAND()*365*2 DAY INTO tbl_name;
SET #MIN = '2019-06-29 00:53:27';
SET #MAX = '2019-06-29 13:53:27';
UPDATE tablename
SET columnname = TIMESTAMPADD(SECOND, FLOOR(RAND() * TIMESTAMPDIFF(SECOND, #MIN, #MAX)), #MIN)
WHERE `columnname` = condition
This worked for me but my issue was a bit different. I had to assign certain values in a column to a random datetime.
UPDATE Tablename
SET columnName = addtime(concat_ws(' ','2018-07-25' + interval rand()*2 day
,'00:00:00'),sec_to_time(floor(0 + (rand() * 86401))))
WHERE columnName = condition;
It's an old thread but still.. In my case I needed to generate random date in format like this : 2017-01-01.
If anyone will need it I have used #drew010 solution and formatted date with DATE_FORMAT.
Here is my code :
SELECT DATE_FORMAT(FROM_UNIXTIME(UNIX_TIMESTAMP('2015-01-01') + FLOOR(0 + (RAND() * 63072000))), '%Y-%m-%d');
Use following dynamic query.
SET #MIN = NOW() - INTERVAL 2 MONTH;
SET #MAX = now();
select TIMESTAMPADD(SECOND, FLOOR(RAND() * TIMESTAMPDIFF(SECOND, #MIN, #MAX)), #MIN)
Thanks to #sapna-bhayal

A simpler way to get the current time in SQL Server 2008

I need to store the current time (format 'hi') as char(4) in a table (is created and used by another program, I can't change it) and now wondered what is a suitable way to retrieve it via SQL. I know MySQL is not that standard-orientated, but I thought it could be something similiar to DATE_FORMAT(NOW(), 'Hi'). The code below which I found works, but feels little intricately.
SELECT CAST(DATEPART(hour, GETDATE()) AS nvarchar)+CAST(DATEPART(minute, GETDATE()) AS nvarchar);
Is there a better way to achieve this?
Following gives the same result:
SELECT LEFT(STUFF(CONVERT(NCHAR(8), GETDATE(), 8), 3, 1,''), 4)
It seems to have approximately the same performance as the method from question. I tested it like this:
DECLARE #i INT = 0,
#dto1 DATETIME2,
#dto2 DATETIME2
SET #dto1 = SYSDATETIME()
WHILE #i < 100000
BEGIN
PRINT LEFT(STUFF(CONVERT(NCHAR(8), GETDATE(), 8), 3, 1,''), 4)
SET #i = #i + 1
END
SET #dto2 = SYSDATETIME()
SELECT DATEDIFF(MILLISECOND, #dto1, #dto2)
Sql Server 2008 has a time datatype:
select replace(left(cast(getdate() as time), 5), ':', '')