auto generate insert script

DECLARE @TableName VARCHAR(128);
SET @TableName = 'Order_Item'
DECLARE @FieldInfo TABLE(FieldName SYSNAME, TypeName SYSNAME);

INSERT INTO @FieldInfo
SELECT c.[name],t.[name]
FROM sys.[columns] c
JOIN sys.types t ON t.user_type_id = c.user_type_id
WHERE c.[object_id] = OBJECT_ID(@TableName);

DECLARE @sql VARCHAR(MAX);
SET @sql = 'select ''insert into ' + @TableName + '(';

SELECT @sql = @sql + FieldName + ','
FROM @FieldInfo

SET @sql = LEFT(@sql,LEN(@sql) - 1) + ') values('''

SELECT 
	@sql = @sql + '
		+ case when ' + FieldName + ' is null then ''NULL'' else '
	+ CASE WHEN TypeName IN('char', 'varchar') THEN ''''''''' + ' + FieldName + ' + ''''''''' 
	ELSE 'cast(' + FieldName + ' as varchar)'
	END + ' end + '','''
FROM @FieldInfo

SET @sql = LEFT(@sql, LEN(@sql) - 2) + ')'' from ' + @TableName
SELECT @sql
posted @ 2010-11-08 17:13  老玉米  阅读(321)  评论(0编辑  收藏  举报