如何检查 table 是否存在然后重命名

How to check table exist and then rename it

这个问题与许多其他问题相似,但它有很多其他问题。

我必须创建一个查询,其中我有很多东西:

First check if table is already exist in the database or not which I know we can get from this

IF (EXISTS (SELECT * 
             FROM INFORMATION_SCHEMA.TABLES 
             WHERE TABLE_SCHEMA = 'TheSchema' 
             AND  TABLE_NAME = 'x'))

Second I need to update the table name if it is already an existing table

EXEC sp_rename 'x','y'

Third I have to check if it is not exist create it and then load the data from text file into database using bcp for that I know code is like this.

Create table x(id int, number varchar(20))

Declare @cmd varchar(200)
Set @cmd='BCP master.dbo.x IN 'filePath' -S -T f -t, -C -E'
EXEC master..XP_CMDSHELL @cmd

我对每一件事都了如指掌 我只需要你的指导 我怎样才能在一个 Sql 查询中实现所有这些。

例如:

I don't have any table with name 'x' in database, so my query first check if their is any table with the name x or not if no then it will create one and load data from bcp, if table is already existing then it will update the name of the table and then load the data using bcp.

Once the file loaded and we have updated name of the table query will run again and it check the table name and same process so I guess I cant take any hard coded value in my query.

更新代码:

Declare @z varchar(100)
Set @z='x' 

IF Object_ID(@z) is null
Print 'Table not EXISTS' 
Else Print 'EXISTS'

 Declare @cmd varchar(200)
Set @cmd='BCP @z IN 'filePath' -S -T f -t, -C -E'
EXEC master..XP_CMDSHELL @cmd

DECALRE @name varchar(200)
set @name= @z+'_'+(convert(varchar(16),GETDATE(),112))
EXEC sp_Rename @z,@name

虽然我只在现有的 table 上工作,但前 2 次它工作正常。 第 3 次它将检查 x table 但在第 2 次尝试时它已经更新为 x_systemdate 现在我只需要知道每次查询 运行.[=19 时如何更改它=]

感谢任何帮助!!

您有更多选择,一种是使用动态查询完成所有操作。您也可以查看 SQLCMD。我将向您展示动态 SQL 解决方案的快速模型。

DECLARE @TableSchema sys.sysname = N'dbo';
DECLARE @TableName sys.sysname = N'x';
DECLARE @BackupTable sys.sysname = @TableName + '_' + CONVERT(VARCHAR(32), GETDATE(), 112);


DECLARE @SQL NVARCHAR(MAX) = N'

DECLARE @TableWithSchema NVARCHAR(256) = QUOTENAME(@TableSchema) + ''.'' + QUOTENAME(@TableName);

IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES 
             WHERE TABLE_SCHEMA = @TableSchema
             AND  TABLE_NAME = @TableName))
BEGIN
  EXEC sp_rename @TableWithSchema, @BackupTable, ''OBJECT''
END

CREATE TABLE ' + QUOTENAME(@TableSchema) + '.' + QUOTENAME(@TableName) + '(
/* Column definitions here*/
);
';

EXEC sp_executesql
    @stmt = @SQL
  , @params = N'@TableSchema sys.sysname, @TableName sys.sysname, @BackupTable sys.sysname'
  , @TableSchema = @TableSchema
  , @TableName = @TableName
  , @BackupTable = @BackupTable
;

/* Do BCP here */

请注意,112 日期格式(请参阅转换)不包含时间值,因此您想更改它以允许脚本一天多次 运行。例如,您可以使用 select REPLACE(REPLACE(REPLACE(CONVERT(VARCHAR(32), GETDATE(), 120), ' ', ''), ':', ''), '-', '') (yyyyMMddHHmmss) 代替

与往常一样,在使用动态查询时要小心并仔细检查您的代码!