Skip to content

Tag: tsql

SQL Server 2017 Convert Varchar to Date

I have a date stored as nvarchar which I cannot seem to convert to a date. I have tried the following but get the error message Conversion failed when converting date and/or time from character string Any ideas here? Answer Find the values that are causing the problem using try_convert(): Once you see what va…

Union ALL with different number of columns

I have an Employee table with these columns : EmployeeId Fullname Phone Department Team Function Manager and EmployeeHistory containing the history with different columns, but there are some in common : EmployeeId Fullname Email Geolocation Department Team Function Manager How can I union them? Answer Replace…

Dynamic SQL stored procedure and datetime

I have a simple query that I want to convert to dynamic SQL. I have 2 input parameters: a table and a datetime. And the output is the rowcount for the table and this specific datetime. I tried different solutions. I tried the query with execute sp_executesql, I tied to add the the ”’ before and af…

SQL Server: Return a string in a specific format

In TSQL, I need to format a string in a predefined format. For eg: SNO STRING FORMAT OUTPUT 1 A5233GFCOP *XXXXX-XXXXX *A5233-GFCOP 2 K92374 /X-000XXXXX /K-00092374 3 H91543987 XXXXXXXXX H91543987 I am trying with FORMATMESSAGE() built in function. For ex: FORMATMESSAGE(‘*%s-%s’,’A5233′…

SQL – Combine two rows if difference is below threshhold

I have a table like this in SQL Server: What I would like to have is a query that outputs consolidated records based on the time difference between two consecutive records (end_time of row n and start_time row n+1) . All records where the time difference is less than 2 minutes should be combined into one time…