SQL临时表的后缀

时间:2019-05-06 18:42:00

标签: sql sql-server prefix

我正在制作一个将表名打印到临时表中的脚本。

我需要这样在后缀

#temptable1 
#temptable2 
...
#temptableXXX

我的问题是,当我使用等级时,它不会增加,并且光标中的身份也不起作用。

我已经发布了两次尝试。其中之一已被注释掉。

DECLARE @suffix VARCHAR(1000)
DECLARE #crs insensitive CURSOR FOR
    SELECT IDENTITY(int, 1, 1) AS ID --rank() over (partition by name order by 
name)  --as Identity(1,1) 
    INTO name
    FROM sys.tables
    FOR READ ONLY

OPEN #crs

FETCH NEXT FROM #crs INTO @suffix 

WHLIE @@FETCH_STATUS = 0
BEGIN
    DECLARE @TableName VARCHAR(100)
    DECLARE @TabName CURSOR

    SET @TabName = CURSOR FOR 
        SELECT NAME + @suffix
        FROM sys.tables 
        ORDER BY name

    OPEN @TabName 

    PRINT '--- Her skal header printes '

    FETCH NEXT FROM @TabName INTO @TableName 

    WHILE @@FETCH_STATUS = 0  
    BEGIN  
        PRINT @TableName
        ----------------------------------------------------------------- start loop tabel

        ----------------------------------------------------------------- slut loop tabel
        Fetch next from @TabName into @TableName 
    END 

    CLOSE @TabName;  
    DEALLOCATE @TabName;   
END

CLOSE #crs 
DEALLOCATE #crs

4 个答案:

答案 0 :(得分:4)

我认为您只是在寻找

rails server -b 0.0.0.0

答案 1 :(得分:0)

首先,不要使用游标:)我会做这样的事情:

DECLARE 
    @Table_Name As Varchar(200)
    , @Message As VarChar(Max)
    , @Suffix As Int = 1
    , @Temp_Table_Name As Varchar(100)


Select Distinct 
    name
    , 0 As Processed
Into #Temp_Names
    from sys.tables

While Exists (Select Top 1 1
    FROM #Temp_Names
        WHERE Processed = 0)    
BEGIN
    Select Top 1 
        @Table_Name = name
            From #Temp_Names
            WHERE Processed = 0
    Set @Temp_Table_Name = 'TempTable' + Cast(@Suffix As Varchar(100))

/*

your code here

*/

    Update #Temp_Names
        Set Processed = 1
    Where name = @Table_Name
    Set @Suffix = @Suffix + 1

End

您可能想要调整Varchar的大小-我是从臀部射击。

答案 2 :(得分:0)

试试这个-

purrr

答案 3 :(得分:0)

另一个解决问题的方法是这个。

declare @nr int = 0;
set @nr = @nr +1 ;
#TmpTab_'+CONVERT(nvarchar(3), @nr)+'