How to Round a Time in T-SQL

Try this function CREATE FUNCTION [dbo].[RoundTime] (@Time datetime, @RoundTo float) RETURNS datetime AS BEGIN DECLARE @RoundedTime smalldatetime DECLARE @Multiplier float SET @Multiplier= 24.0/@RoundTo SET @RoundedTime= ROUND(CAST(CAST(CONVERT(varchar,@Time,121) AS datetime) AS float) * @Multiplier,0)/@Multiplier RETURN @RoundedTime END select dbo.roundtime(’13:15′,0.5) The 1st param is the time to be rounded and the 2nd will be base on your list … Read more

How to insert default values in SQL table?

Best practice it to list your columns so you’re independent of table changes (new column or column order etc) insert into table1 (field1, field3) values (5,10) However, if you don’t want to do this, use the DEFAULT keyword insert into table1 values (5, DEFAULT, 10, DEFAULT)

T-SQL loop over query results

You could use a CURSOR in this case: DECLARE @id INT DECLARE @name NVARCHAR(100) DECLARE @getid CURSOR SET @getid = CURSOR FOR SELECT table.id, table.name FROM table OPEN @getid FETCH NEXT FROM @getid INTO @id, @name WHILE @@FETCH_STATUS = 0 BEGIN EXEC stored_proc @varName=@id, @otherVarName=”test”, @varForName=@name FETCH NEXT FROM @getid INTO @id, @name END CLOSE … Read more

T-SQL Pivot? Possibility of creating table columns from row values

Itzik Ben-Gan’s example on how to build dynamic PIVOT, I highly recommend his Inside Microsoft SQL Server 2008: T-SQL Programming book — Creating and Populating the Orders Table USE tempdb; GO IF OBJECT_ID(‘dbo.Orders’) IS NOT NULL DROP TABLE dbo.Orders; GO CREATE TABLE dbo.Orders ( orderid int NOT NULL PRIMARY KEY NONCLUSTERED, orderdate datetime NOT NULL, … Read more

Selecting a Record With MAX Value

Note: An incorrect revision of this answer was edited out. Please review all answers. A subselect in the WHERE clause to retrieve the greatest BALANCE aggregated over all rows. If multiple ID values share that balance value, all would be returned. SELECT ID, BALANCE FROM CUSTOMERS WHERE BALANCE = (SELECT MAX(BALANCE) FROM CUSTOMERS)