Digital Lifestyle

Tag: sql

MSSQL int to nvarchar

If you need to convert/cast a database integer field to an nvarchar on a Microsoft SQL Server, you should use the convert function. In this example we cast the number 4343 to an nvarchar:

	convert(nvarchar(255), 4343)

Example to convert an int field (field_int) to a nvarchar field:

SELECT field_int,
	convert(nvarchar(255), field_int) as field_as_nvarchar
FROM [TEST].[dbo].[TestTable]

Result from the query:

MSSQL datediff in seconds

The following command on a Microsoft SQL Server calculates the difference in seconds between two datetimes:

DATEDIFF(SECOND, date1, date2)

Example query:

	  DATEDIFF(SECOND, date1, date2) / 1000  as difference_in_seconds
  FROM [TEST].[dbo].[TestTableDatetime]


If you need the result as a text and also want to add 3 digits after the seconds you can use the following example:

	CONVERT(VARCHAR(12),  DATEDIFF(MILLISECOND, date1, date2) / 1000)  + ','   
	+ RIGHT('000' + CONVERT(VARCHAR(4), DATEDIFF(MILLISECOND, date1, date2) % 1000), 3) 
		as difference_in_seconds_as_text
FROM [TEST].[dbo].[TestTableDatetime]


Oracle top 1 record

To select the top 1 records from an oracle database, you filter with the where statement on rownum = 1:

select * from my_table where rownum = 1

If you want to select top 10 records from the table you use the following statement:

select * from my_table where rownum <= 10

© 2021 Jannik Strelow

Theme by Anders NorenUp ↑