Home >Backend Development >PHP Tutorial >PHP tutorial on merging user log tables in SQL Server
In the process of maintaining the SQL Server database, do you often encounter thousands of log tables similar to log20050901? There is not a lot of data in each table, and it is very inconvenient to open them one by one, or sometimes we need to It is also very troublesome to summarize the data in these tables and open them one by one. The following introduces an automated method of merging tables.
My idea is to create a user stored procedure to complete a series of automated operations. The following is the code.
--I named the stored procedure BackupData, you can use your own defined name.
--Parameter 1: @TableTarget The name of the generated target table
--Parameter 2: @TableStart The name of the table where the merge starts
--Parameter 3: @TableEnd The name of the table where the merging ends
CREATE PROCEDURE BackupData @TableTarget sysname,@TableStart sysname,@TableEnd sysname
AS
DECLARE tnames_cursor CURSOR
FOR
SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
OPEN tnames_cursor
DECLARE @TableName sysname
DECLARE @TablePref sysname
DECLARE @IsTargetExist integer
--determine whether the target table exists
SET @IsTargetExist=(SELECT count(TABLE_NAME) FROM INFORMATION_SCHEMA.TABLES where table_name = @TableTarget )
--If the target table does not exist, create a new table
IF @istargetexist=0
BEGIN
--The statements in EXEC can be replaced with table scripts written in SQL Server. Note that there cannot be an "auto number" type field in the target table with the same name as the one in the table to be merged.
EXEC ('CREATE TABLE [dbo].[' @TableTarget ']
(
[LOG1] [nvarchar] (10) COLLATE Chinese_PRC_CI_AS NULL ,
[LOG2] [nvarchar] (10) COLLATE Chinese_PRC_CI_AS NULL ,
……
)')
END
FETCH NEXT FROM tnames_cursor INTO @TableName
WHILE (@@FETCH_STATUS <> -1)
BEGIN
IF (@@FETCH_STATUS <> -2)
BEGIN
SELECT @TableName = RTRIM(@TableName)
--The following two lines are changed according to the name of the log table
-- Take the first 3 digits of the log table name as the identifier
SELECT @TablePref = LEFT(@TableName,3)
-- Determine whether the table name meets the requirements
IF (@TablePref='log') and (@TableName>=@TableStart) and (@TableName<=@TableEnd)
--Start import