Showing posts with label SQL Server. Show all posts
Showing posts with label SQL Server. Show all posts

May 8, 2009

Copy SQL Server database tables

Ever needed to copy an SQL Server database, but get only its data and leave out everything else?
Here's a T-SQL script that you can use to copy all the database's tables' data, and leave out everything else (indexes, partitions, programmability components, etc...)
The script will go through all tables in the 'dbo' schema of the source database (named 'sourceDatabase' in this example), create a copy of the table in the 'dbo' schema of the destination database (named 'targetDatabase') and insert all data from the source table in the destination table (by using a SELECT INTO).

Here's the code:

DECLARE @tableName varchar(300)
DECLARE @sqlStmt nvarchar(300)

DECLARE curTables CURSOR LOCAL FOR
SELECT table_name FROM sourceDatabase.INFORMATION_SCHEMA.tables


OPEN curTables

FETCH NEXT FROM curTables INTO @tableName
WHILE @@FETCH_STATUS = 0
BEGIN
SET @sqlStmt = 'SELECT * INTO targetDatabase.dbo.' + @tableName + ' FROM sourceDatabase.dbo.' + @tableName
EXEC sp_executesql @sqlStmt

FETCH NEXT FROM curTables INTO @tableName
END

CLOSE curTables
DEALLOCATE curTables

December 27, 2007

How to reset SQL Server identity column

Generally, to reset an identity column to value n on table XYZ:
DBCC CHECKIDENT('XYZ',RESEED,n)

So, to reset an identity column to value 17 on table XYZ:
DBCC CHECKIDENT('XYZ',RESEED,17)

October 16, 2007

Get the datetime representing the first day of a date

This is pretty useful when you need to get data from the past n months:

SELECT CAST(((convert(varchar(7),getdate(),121))+'-01') AS datetime)

Get the date portion of a datetime

SELECT CONVERT(varchar(11), myDate, 102)
You can then use REPLACE() to substitute the . with -