t-sql get all dates between 2 dates [duplicate]

Assuming SQL Server 2005+, use a recursive query: WITH sample AS ( SELECT CAST(‘2010-12-01’ AS DATETIME) AS dt UNION ALL SELECT DATEADD(dd, 1, dt) FROM sample s WHERE DATEADD(dd, 1, dt) <= CAST(‘2010-12-04’ AS DATETIME)) SELECT * FROM sample Returns: dt ——— 2010-12-01 00:00:00.000 2010-12-02 00:00:00.000 2010-12-03 00:00:00.000 2010-12-04 00:00:00.000 Use CAST/CONVERT to format as … Read more

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

What is a “batch”, and why is GO used?

GO is not properly a TSQL command. Instead it’s a command to the specific client program which connects to an SQL server (Sybase or Microsoft’s – not sure about what Oracle does), signalling to the client program that the set of commands that were input into it up till the “go” need to be sent … 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