----------------------------存储过程1-------------------------------------(请分两部分执行)
IF EXISTS (SELECT * FROM DBO.SYSOBJECTS WHERE ID =OBJECT_ID(N'[DBO].[P_CREATETABLE]') AND OBJECTPROPERTY(ID, N'ISPROCEDURE')= 1)
-- 删除存储过程
DROP PROCEDURE [DBO].[P_CREATETABLE]
GO
CREATE PROC [DBO].[P_CREATETABLE] @vTABLENAME VARCHAR(100),@DBNAME VARCHAR(100) AS
SET NOCOUNT ON
If Object_Id('dbo.#SQLTable') Is Null
BEGIN
CREATE TABLE #SQLTable
(TABLENAME VARCHAR(50),
B_NAME VARCHAR(50),
B_PRECISION INT,
B_SCALE INT,
B_MAX_LENGTH INT,
B_IS_IDENTITY INT,
B_IS_NULLABLE INT,
C_NAME VARCHAR(50),
C_COLLATION_NAME VARCHAR(50),
D_DEFINITION VARCHAR(50)
)
END
DECLARE @SQL VARCHAR(MAX),@vSQL VARCHAR(MAX),@TABLENAME VARCHAR(100)
SET @TABLENAME =@vTABLENAME--这里输入表名
SET @vSQL='USE '+ @DBNAME +
' INSERT INTO #SQLTable(TABLENAME,B_NAME,B_PRECISION,B_SCALE,B_MAX_LENGTH,B_IS_IDENTITY,B_IS_NULLABLE,C_NAME,
C_COLLATION_NAME,D_DEFINITION)
SELECT '''+@TABLENAME+''', B.NAME,B.PRECISION,B.SCALE,B.MAX_LENGTH,B.IS_IDENTITY,B.IS_NULLABLE,C.NAME,C.COLLATION_NAME,D.DEFINITION
FROM SYS.OBJECTS A JOIN SYS.COLUMNS B
ON A.OBJECT_ID = B.OBJECT_ID
JOIN SYS.TYPES C
ON B.SYSTEM_TYPE_ID = C.SYSTEM_TYPE_ID AND B.USER_TYPE_ID = C.USER_TYPE_ID
LEFT JOIN SYS.DEFAULT_CONSTRAINTS D
ON B.DEFAULT_OBJECT_ID = D.OBJECT_ID
WHERE A.NAME='''+@TABLENAME+
'''ORDER BY B.COLUMN_ID'
exec (@vSQL)
SET @SQL = 'IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'''+@TABLENAME+''') AND type in (N''U''))
BEGIN
CREATE TABLE ['+@TABLENAME+']
('
SELECT @SQL = @SQL + B_NAME + ' '+C_NAME+
CASE WHEN ( C_NAME='binary' OR C_NAME='char' OR C_NAME='decimal' OR C_NAME='nchar'
OR C_NAME='numeric' OR C_NAME='nvarchar' OR C_NAME='varbinary' OR C_NAME='varchar' )
THEN '('+
CASE WHEN(C_NAME='decimal' OR C_NAME='numeric')
THEN CONVERT(VARCHAR(20),B_PRECISION) +','+CONVERT(VARCHAR(20),B_SCALE)
WHEN((C_NAME='binary' OR C_NAME='char'OR C_NAME='varbinary' OR C_NAME='varchar' )AND B_MAX_LENGTH <>-1)
THEN CONVERT(VARCHAR(20),B_MAX_LENGTH)
WHEN((C_NAME='nchar' OR C_NAME='nvarchar')AND B_MAX_LENGTH <>-1)
THEN CONVERT(VARCHAR(20),(B_MAX_LENGTH/2))
ELSE 'MAX'END
+') '
ELSE ''
END +
CASE WHEN(C_COLLATION_NAME IS NOT NULL)
THEN
- 1
- 2
前往页