Tag Archives

2 Articles

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:

SELECT
	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:

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

Result:

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

SELECT 
	date1,
	date2,
	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]

Result: