简体   繁体   English

一个SQL Server 2005 Express查询,它将为每个数据库添加一个表

[英]A SQL Server 2005 Express query that will add a table per database

Here is the query that I am trying to run 这是我要运行的查询

DECLARE @str VARCHAR(10)
DECLARE @index int
DECLARE @SQL VARCHAR(100)
DECLARE @SQL2 VARCHAR(300)
DECLARE @SQL3 VARCHAR(400)

SET @str = 'DB'
SET @index = 0

WHILE @index < 100
BEGIN
    SET @SQL = 'use ' + @str + CASE 
                   WHEN @index < 10 THEN '00'
                   WHEN @index < 100 THEN '0'
                   ELSE ''
                   END + CAST(@index as VARCHAR)
    EXEC(@SQL)
    GO

    CREATE TABLE Persons
    (
        PersonID int,
        LastName varchar(255),
        FirstName varchar(255),
        Address varchar(255),
        City varchar(255)
    );

    set @index = @index + 1
END

which I think should create a table per database in the databases named DB000 to DB099 but I get 3 syntax errors they are posted below 我认为应该在名为DB000DB099的数据库中为每个数据库创建一个表,但是我收到3个语法错误,它们在下面发布

Msg 102, Level 15, State 1, Line 18 Msg 102,第15级,第1行,第18行
Incorrect syntax near ')'. ')'附近的语法不正确。

Msg 137, Level 15, State 2, Line 9 消息137,第15级,州2,第9行
Must declare the scalar variable "@index". 必须声明标量变量“ @index”。

Msg 137, Level 15, State 2, Line 11 消息137,第15级,州2,第11行
Must declare the scalar variable "@index". 必须声明标量变量“ @index”。

Can someone help me out in making this work correctly? 有人可以帮我完成这项工作吗? Or at least point me in the right direction? 或至少指出我正确的方向?

This should work if you need this one table to be created in databases named DB000 to DB099: 如果您需要在名为DB000到DB099的数据库中创建此表,这应该起作用:

       DECLARE @str VARCHAR(10)
       DECLARE @index int
       DECLARE @SQL VARCHAR(100)
       DECLARE @SQL2 VARCHAR(300)
       DECLARE @SQL3 VARCHAR(400)


       SET @str = 'DB'
       SET @index = 0

       WHILE @index < 100
       BEGIN
       SET @SQL = @str + CASE 
               WHEN @index < 10 THEN '00'
               WHEN @index < 100 THEN '0'
               ELSE ''
       END + CAST(@index as VARCHAR)
       PRINT @SQL
       -- EXEC(@SQL)

       SET @SQL2 = 'CREATE TABLE ' + @SQL + '..Persons
         (
          PersonID int,
          LastName varchar(255),
          FirstName varchar(255),
          Address varchar(255),
          City varchar(255)
          );'
        EXEC(@SQL2)

       set @index = @index + 1
       END

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM