SQL _server converts a record in a table into an insert SQL statement

Source: Internet
Author: User
Create proc spgeninsertsql @ tablename as varchar (100) as -- declare @ tablename varchar (100) -- set @ tablename = 'Orders '-- set @ tablename = 'education' declare xcursor cursor for select name, xusertype from syscolumns where (ID = object_id (@ tablename )) declare @ F1 varchar (100) Declare @ F2 integer declare @ SQL varchar (8000) set @ SQL = 'select' insert into '+ @ tablename + 'values (''' open xcursor fetch xcursor into @ F1, @ F2 while @ fetch_status = 0 begin set @ SQL = @ SQL ++ case when @ F2 in (99,167,175,231,239, 61) then' + case when' + @ F1 + 'is null then''' else ''' end + 'else' + 'end + 'replace (isnull (cast ('+ @ F1 +' As varchar (8000 )), ''null''), ''' + case when @ F2 in, 99,167,175,231,239, 61) then' + case when' + @ F1 + 'is null then''' else ''' end + 'else' + 'end + char (13) + ''', ''' fetch next from xcursor into @ F1, @ F2 end close xcursor deallocate xcursor set @ SQL = left (@ SQL, Len (@ SQL)-5) + '+ '') ''from' + @ tablename exec (@ SQL) Go

 

 

The above code is run in the query analyzer.

Run again

Exec spgeninsertsql tablename -- Name of the table to be converted

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.