SQL Server: How to get all child records given a parent id in a self referencing table

You can try this DECLARE @Table TABLE( ID INT, ParentID INT, NAME VARCHAR(20) ) INSERT INTO @Table (ID,ParentID,[NAME]) SELECT 1, NULL, ‘A’ INSERT INTO @Table (ID,ParentID,[NAME]) SELECT 2, 1, ‘B-1’ INSERT INTO @Table (ID,ParentID,[NAME]) SELECT 3, 1, ‘B-2’ INSERT INTO @Table (ID,ParentID,[NAME]) SELECT 4, 2, ‘C-1’ INSERT INTO @Table (ID,ParentID,[NAME]) SELECT 5, 2, ‘C-2’ DECLARE … Read more

SQL Server Count is slow

Very close approximate (ignoring any in-flight transactions) would be: SELECT SUM(p.rows) FROM sys.partitions AS p INNER JOIN sys.tables AS t ON p.[object_id] = t.[object_id] INNER JOIN sys.schemas AS s ON s.[schema_id] = t.[schema_id] WHERE t.name = N’myTable’ AND s.name = N’dbo’ AND p.index_id IN (0,1); This will return much, much quicker than COUNT(*), and if … Read more

How to update data in one table from corresponding data in another table in SQL Server 2005

If the two databases are on the same server, you should be able to create a SQL statement something like this: UPDATE Test1.dbo.Employee SET DeptID = emp2.DeptID FROM Test2.dbo.Employee as ’emp2′ WHERE Test1.dbo.Employee.EmployeeID = emp2.EmployeeID From your post, I’m not quite clear whether you want to update Test1.dbo.Employee with the values from Test2.dbo.Employee (that’s what … Read more

Get top first record from duplicate records having no unique identity

Find all products that has been ordered 1 or more times… (kind of duplicate records) SELECT DISTINCT * from [order_items] where productid in (SELECT productid FROM [order_items] group by productid having COUNT(*)>0) order by productid To select the last inserted of those… SELECT DISTINCT productid, MAX(id) OVER (PARTITION BY productid) AS LastRowId from [order_items] where … Read more

SQL server identity column values start at 0 instead of 1

From DBCC CHECKIDENT DBCC CHECKIDENT ( table_name, RESEED, new_reseed_value ) If no rows have been inserted to the table since it was created, or all rows have been removed by using the TRUNCATE TABLE statement, the first row inserted after you run DBCC CHECKIDENT uses new_reseed_value as the identity. Otherwise, the next row inserted uses … Read more