Working with SQL Essays

Source: Internet
Author: User

SQL loop

--All tables that need to be backed upDECLARE @fromtbs NVARCHAR( -)='HZ_COM_USER,HZ_BAM_DEPARTMENT,HZ_HR_GZHSFW,HZ_HR_XIAOWEICOMPANY,HZ_COM_PARAMETER,HZ_BAM_POSITION,HZ_BAM_ Dep_target,hz_bom_userall_maincofnig,',@index INT,--', ' where you cut all the tables into a single table@fromtable NVARCHAR( -),--the name of the original table that needs to be backed up@totable NVARCHAR( -),--the name of the new table to be backed up@insertfields NVARCHAR( +)="',--insert time and table name corresponding to str@sql NVARCHAR( the),--SQL statement to execute because the table name is a variable@temptablename NVARCHAR( -)--table name for temporary stitching--looping using the index and SUBSTRING methods--gets the first, where the number is locatedSET @index=(SELECT CHARINDEX(',',@fromtbs))--Start Loop while @index>0BEGIN--truncate the name of the table where the first position is locatedSET @fromtable=(SELECT SUBSTRING(@fromtbs,1,@index-1))--intercept all remaining tables that need to be backed up for Next loop interceptionSET @fromtbs =(SELECT SUBSTRING(@fromtbs,@index+1,LEN(@fromtbs)))--Name the table you want to back upSET @totable=@fromtable+'_bak_'+(SELECT CONVERT(varchar( -),GETDATE(), the))        --If there is a delete does not exist select the original table into backup table    SET @sql = 'IF EXISTS (SELECT * from sys.objects WHERE object_id = object_id (N"'[dbo].'+@totable+" '"+') ) DROP table'+@totable    EXEC(@sql)    SET @sql='SELECT * into'+@totable+'From hrms_pro_20170401.dbo.'+@fromtable+"'    EXEC(@sql)    --Splicing all backup table names for easy insertion into the R_date_and_tablename table    SET @insertfields+=('," "+@totable+" '")SET @index=(SELECT CHARINDEX(',',@fromtbs))END
View Code

Working with SQL Essays

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.