这又如何在SQL(MS SQL)来实现创建另一个表的结构表无数据
感谢
OK:让我有点不清楚什么我试图acheive正在生成动态的select语句EXCEPT子句。
例如:选择COL1,COL2,从@table COL3除了 选择COL1,COL2,从@table
COL2所以我的结果集将根据@table
futher下来,我想总是不同以使用该@table在CTE
与filteredData 如 ( 选择COL1,COL2从不是Temptable - (上面创建) )
以下是迄今为止代码:
DECLARE @TABLENAME VARCHAR(200) = 'SERVICE_DELIVERY_LOCATION';
DECLARE @COLCOUNT INT ;
DECLARE @TEMPCOLNAME VARCHAR(500) ;
DECLARE @SELECTCOLUMNS VARCHAR(5000)='';
DECLARE @EXCEPTSTATEMENT VARCHAR(5000)='' ;
---------------------------------------------------------------------------------------------------
--CASE: GET COMMON_COLUMNS COLUMNS OF SOURCE AND DESTINATION TABLE
---------------------------------------------------------------------------------------------------
DECLARE @COMMON_COLUMNS TABLE(COLUMN_NAME VARCHAR(500))
INSERT INTO @COMMON_COLUMNS
SELECT SOURCE.COLUMN_NAME FROM SCD_SOURCE.INFORMATION_SCHEMA.COLUMNS SOURCE
INNER JOIN SCD_DESTI.INFORMATION_SCHEMA.COLUMNS DESTI ON SOURCE.COLUMN_NAME = DESTI.COLUMN_NAME
---------------------------------------------------------------------------------------------------
--CASE: GET PK COLUMNS OF SOURCE TO MAP TO DESTINATION IN CASE WHERE NEED TO DO UPDATES
---------------------------------------------------------------------------------------------------
DECLARE @PK_COLUMNS TABLE (PK_COLUMN VARCHAR(500))
INSERT INTO @PK_COLUMNS
SELECT KCU.COLUMN_NAME
FROM SCD_SOURCE.INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TC
JOIN SCD_SOURCE.INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KCU ON KCU.CONSTRAINT_SCHEMA = TC.CONSTRAINT_SCHEMA
AND KCU.CONSTRAINT_NAME = TC.CONSTRAINT_NAME
AND KCU.TABLE_SCHEMA = TC.TABLE_SCHEMA
AND KCU.TABLE_NAME = TC.TABLE_NAME
AND KCU.COLUMN_NAME != 'CREATE_DATA_CONTAINER_ID'
WHERE TC.CONSTRAINT_TYPE IN ('PRIMARY KEY')
SELECT @COLCOUNT = COUNT(*) FROM @COMMON_COLUMNS
WHILE (@COLCOUNT != 0)
BEGIN
SET @TEMPCOLNAME = (SELECT TOP 1 COLUMN_NAME FROM @COMMON_COLUMNS)
SET @SELECTCOLUMNS = @SELECTCOLUMNS + @TEMPCOLNAME + ', '
DELETE FROM @COMMON_COLUMNS WHERE COLUMN_NAME = @TEMPCOLNAME
SELECT @COLCOUNT = COUNT(*) FROM @COMMON_COLUMNS
END
SET @SELECTCOLUMNS = SUBSTRING(@SELECTCOLUMNS, 1, LEN(@SELECTCOLUMNS) - 1)
SET @EXCEPTSTATEMENT = 'SELECT ' + @SELECTCOLUMNS + ' FROM SCD_SOURCE.DBO.' + @TABLENAME + ' EXCEPT SELECT ' + @SELECTCOLUMNS + ' FROM SCD_DESTI.DBO.' + @TABLENAME
EXEC(@EXCEPTSTATEMENT)
想最后一行的结果集到不是Temptable
感谢
程序是否必须使用相同的模式创建新表?如果它是由人类anthares完成是正确的。 – awright18 2010-02-19 13:03:38