|
jaskalirai
Starting Member
31 Posts |
Posted - 2007-12-13 : 14:20:59
|
| declare @TableName varchar(50),@SqlCode varchar(max),@columnOrder varchar (50),@ColumnName varchar(50),@DataType varchar(50),@length varchar(50),@Precision Varchar (50),@Collation varchar(50),@Nullable varchar (50),@MaxColumnId int select @tablename = 'TestTable'select @maxcolumnid = max(columnorder)from code where tablename = @tablenamedeclare tabledetails cursor forSelect -- [TableName],[ColumnOrder],[ColumnName],[DataType],isnull([Length],''), [Precision],[Collation],case [Nullable] when 'yes' then 'Null' else 'not null' endfrom codeorder by columnorderopen tabledetailsfetch next from tabledetails into @columnOrder, @columnName, @Datatype, @Length, @precision, @collation, @nullablewhile @@fetch_Status = 0Begin If @ColumnOrder = 1 Begin Select @sqlCode = 'CREATE TABLE [dbo].[' + @TableName + '] ( [' + @ColumnName + '] [' + @DataType + '] (' + case when @Length = '' then + ' ' + @length + ' ' else ' (' + @length + ')' end + case when @precision is null then ') ' else ',' + @precision + ') ' end + @Nullable + ','End If @columnorder <> 1 and @columnOrder <> @MaxcolumnidBeginSelect @sqlCode = @SqlCode + ' [' + @ColumnName + '] [' + @Datatype + ']' if @length <> ''BEGIN SELECT @sqlcode = @sqlcode + ' (' + @length + ') ' + @nullable + ','END if @length = ''BEGIN SELECT @sqlcode = @sqlcode + ' ' + @length + ' ' + @nullable + ','END --select @columnOrder, @columnName, @Datatype, @Length, @precision, @collation, @nullableEndIf @columnorder = @MaxcolumnidBeginSelect @sqlCode = @SqlCode + ' [' + @ColumnName + '] [' + @Datatype + '] (' + @length + ') ' + @nullable + ' ) ON [Primary] '--select @columnOrder, @columnName, @Datatype, @Length, @precision, @collation, @nullableEndfetch next from tabledetails into @columnOrder, @columnName, @Datatype, @Length, @precision, @collation, @nullable EndClose tabledetailsDeallocate tabledetails --select * from code where tablename = @tablename select @sqlcode as sqlcode Below is what sqlcode return when i execute the query CREATE TABLE [dbo].[TestTable] ( [Column1] [int] ( ) not null, [Column2] [varchar] (7) not null, [Column3] [bit] not null, [Column4] [varchar] (55) Null, [Column5] [varchar] (12) Null, [Column6] [varchar] (24) Null, [Column7] [varchar] (56) Null ) ON [Primary] what i am having trouble with 1. i want to get rid of the brackets where the datatype is not varchar >>>> [Column1] [int] ( ) 2. i also want to add the precision and collation into the code so the code reads as follows @columnOrder, @columnName, @Datatype, @Length, @precision, @collation, @nullableI have tried everything i can think of including nested statements |
|