DECLARE @COLNAME VARCHAR(100)
DECLARE @CREATE VARCHAR (1000)
DECLARE @TYPE VARCHAR(1)
SET @COLNAME = ''
SET @TYPE = 5
SET @CREATE = 'CRATE TABLE TABLE_TYPE_' + @TYPE + '('
DECLARE MyCursor CURSOR FOR
SELECT Name FROM LAYOUT WHERE RecordType = @TYPE
ORDER BY Start
OPEN MyCursor
FETCH NEXT FROM MyCursor INTO @COLNAME
WHILE @@FETCH_STATUS = 0
BEGIN
SET @COLNAME = REPLACE(@COLNAME, 'WX-', '')
SET @COLNAME = REPLACE(@COLNAME, '(', '')
SET @COLNAME = REPLACE(@COLNAME, ')', '')
SET @CREATE = @CREATE + '[' + @COLNAME + ']' + ' VARCHAR(1000),'
FETCH NEXT FROM MyCursor INTO @COLNAME
END
CLOSE MyCursor
DEALLOCATE MyCursor
SET @CREATE = LEFT(@CREATE, len(@CREATE) -1) + ')' --get rid of last comma
PRINT (@CREATE) --EXEC (@CREATE)
似乎MS的最大限制。当我打印@CREATE时,许多行已被切断。 EX。有300列但不知何故它只能打印出200列 如何在不中断的情况下生成create table语句。
我知道有些人会建议不要使用光标,但由于一个表的列数太多,因此输入所有列名称将非常耗时。
答案 0 :(得分:3)
你真的不应该使用光标。 不仅可以不使用光标,它更简单:
DECLARE @CREATE VARCHAR (max),
@TYPE int = 5
SET @CREATE = 'CRATE TABLE TABLE_TYPE_' + CAST(@TYPE as varchar) + '('
SELECT @CREATE = @CREATE + REPLACE(
REPLACE(
REPLACE([Name], 'WX-', ''),
'(', ''),
')', '') + ' VARCHAR(1000),'
FROM Layout
WHERE RecordType = @TYPE
SET @CREATE = LEFT(@CREATE, len(@CREATE) -1) + ')' --get rid of last comma
PRINT @CREATE