在SQL2000怎樣用動態實現SQL2005的nvarchar(max)功能

最近發現還有網友在提SQL2000的字符限制問題,以下舉一個例給大家參照:

--動態建表:

 

use Tempdb
go
if object_id('SP_CreateTable') is not null
    drop proc SP_CreateTable
go
create Procedure SP_CreateTable(
                    @TabName sysname,--表名
                    @SQLCol nvarchar(200)='',--固定列和類型定義
                    @COLS nvarchar(4)=1,--新建列數
                    @COL nvarchar(50)='COL'--列的開始字符定義
)
as
if @COLS not between 1 and 1024
    begin
        select N'列數指定不正確' as Error
        return
    end
if @SQLCol>''
    set @SQLCol=@SQLCol+','

declare @s1 nvarchar(4000),@s2 nvarchar(4000),@s3 nvarchar(4000),@s4 nvarchar(4000),@j nvarchar(4)

select @s1='',@s2='',@s3='',@s4='',@j=1

while @j<=(@COLS-1)/100+1
begin
    select @s1=@s1+',@'+@j+' nvarchar(4000)'
            ,@s2=@s2+',@'+@j+'='''''
            ,@s3=@s3+',@'+@j+'=case when (@i-1)/100+1='+@j+' then @'+@j+'+'',''+'''+@COL+'''+@i+'' int'' else @'+@j+' end'
            ,@s4=@s4+'+@'+@j
            ,@j=@j+1
end
select    @s1=stuff(@s1,1,1,'declare ')+',@i nvarchar(4)'
        ,@s2=stuff(@s2,1,1,'select ')+',@i=1'
        ,@s3=stuff(@s3,1,1,'select ')+',@i=@i+1'
        ,@s4='exec('+stuff(@s4,1,1,'''create table '+@TabName+'('+@SQLCol+'''+')+'+'')'')'

exec(@s1+' '+@s2+' while @i<='+@COLS+' '+@s3+' set @1=stuff(@1,1,1,'''') '+@s4)

go

exec SP_CreateTable @TabName='Temp1'
exec SP_CreateTable @TabName='Temp2',@SQLCol='ID int identity primary key'
exec SP_CreateTable @TabName='Temp3',@SQLCol='ID int identity primary key',@COLS=40
exec SP_CreateTable @TabName='Temp4',@SQLCol='ID int identity primary key',@COLS=1023,@COL='ROY'

select * from Temp1
select * from Temp2
select * from Temp3
select * from Temp4

drop table temp1,Temp2,Temp3,temp4


原文链接: http://blog.csdn.net/roy_88/article/details/4407165

你可能感兴趣的:(在SQL2000怎樣用動態實現SQL2005的nvarchar(max)功能)