Generate a resultset of incrementing dates in TSQL

If your dates are no more than 2047 days apart: declare @dt datetime, @dtEnd datetime set @dt = getdate() set @dtEnd = dateadd(day, 100, @dt) select dateadd(day, number, @dt) from (select number from master.dbo.spt_values where [type] = ‘P’ ) n where dateadd(day, number, @dt) < @dtEnd I updated my answer after several requests to do … Read more

How to store directory / hierarchy / tree structure in the database?

There are many ways to store hierarchies in SQL databases. Which one to choose depends on which DBMS product you use, and how the data will be used. As you have used the MSSQL2005 tag, I think you should start considering the “Adjacency List” model; if you find that it doesn’t perform well for your … Read more

How do I avoid character encoding when using “FOR XML PATH”?

You just need to use the right options with FOR XML. Here’s one approach that avoids encoding: USE tempdb; GO CREATE TABLE dbo.x(y nvarchar(255)); INSERT dbo.x SELECT ‘Sports & Recreation’ UNION ALL SELECT ‘x >= y’ UNION ALL SELECT ‘blat’ UNION ALL SELECT ‘<hooah>’; — BAD: SELECT STUFF((SELECT N’,’ + y FROM dbo.x FOR XML … Read more

Import Package Error – Cannot Convert between Unicode and Non Unicode String Data Type

The problem of converting from any non-unicode source to a unicode SQL Server table can be solved by: add a Data Conversion transformation step to your Data Flow open the Data Conversion and select Unicode for each data type that applies take note of the Output Alias of each applicable column (they are named Copy … Read more

Parameter Sniffing (or Spoofing) in SQL Server

FYI – you need to be aware of something else when you’re working with SQL 2005 and stored procs with parameters. SQL Server will compile the stored proc’s execution plan with the first parameter that’s used. So if you run this: usp_QueryMyDataByState ‘Rhode Island’ The execution plan will work best with a small state’s data. … Read more

Convert Xml to Table SQL Server

This is the answer, hope it helps someone 🙂 First there are two variations on how the xml can be written: 1 <row> <IdInvernadero>8</IdInvernadero> <IdProducto>3</IdProducto> <IdCaracteristica1>8</IdCaracteristica1> <IdCaracteristica2>8</IdCaracteristica2> <Cantidad>25</Cantidad> <Folio>4568457</Folio> </row> <row> <IdInvernadero>3</IdInvernadero> <IdProducto>3</IdProducto> <IdCaracteristica1>1</IdCaracteristica1> <IdCaracteristica2>2</IdCaracteristica2> <Cantidad>72</Cantidad> <Folio>4568457</Folio> </row> Answer: SELECT Tbl.Col.value(‘IdInvernadero[1]’, ‘smallint’), Tbl.Col.value(‘IdProducto[1]’, ‘smallint’), Tbl.Col.value(‘IdCaracteristica1[1]’, ‘smallint’), Tbl.Col.value(‘IdCaracteristica2[1]’, ‘smallint’), Tbl.Col.value(‘Cantidad[1]’, ‘int’), Tbl.Col.value(‘Folio[1]’, ‘varchar(7)’) FROM @xml.nodes(‘//row’) Tbl(Col) … Read more