SQL generates the insert language name based on the table structure and data.

Source: Internet
Author: User
Declare @ Tablename Varchar (256)

Set@ Tablename = 'yp_drugname'

Declare @ SQL Varchar (8000)
Declare @ Sqlvalues Varchar (8000)
Set @ SQL = '('
Set @ Sqlvalues = 'values (''+'
Select @ Sqlvalues = @ sqlvalues + Cols + '+ '','' + ',@ SQL = @ SQL + '[' + [ Name ] + '],'
From
( Select Case
When Xtype In (104,106,108,122,127)
Then 'Case when' + [ Name ] + 'Is null then' 'null' 'else' + 'Cast ('+ [ Name ] + 'As varchar) '+ 'end'
When Xtype In (58,61)
Then 'Case when' + [ Name ] + 'Is null then' 'null' 'else' + ''' + 'cast (' + [ Name ] + 'As varchar) '+ ''' + 'end'
When Xtype In (167)
Then 'Case when' + [ Name ] + 'Is null then' 'null' 'else' + ''' + 'Replace (' + [ Name ] + ','''''''','''''''''''') '+ ''' + 'End'
When Xtype In (231)
Then 'Case when' + [ Name ] + 'Is null then' 'null' 'else' + '''n' ''' + '+ 'replace (' + [ Name ] + ','''''''','''''''''''') '+ ''' + 'End'
When Xtype In (175)
Then 'Case when' + [ Name ] + 'Is null then'' 'null''' else '+ ''' +' cast (replace ('+ [ Name ] + ', ''', ''') As char (' + Cast ( Length As Varchar ) + ') + ''' + 'End'
When Xtype In (239)
Then 'Case when' + [ Name ] + 'Is null then' 'null' 'else' + '''n' ''' + '+ 'Cast (replace (' + [ Name ] + ', ''', ''') As char (' + Cast ( Length As Varchar ) + ') + ''' + 'End' Else '''Null '''
End As Cols ,[ Name ] From Syscolumns Where Id = object_id (@ tablename)
) T
Set @ SQL = 'Select' insert into ['+ @ tablename +'] '+ Left (@ SQL , Len (@ SQL )-1) + ')' + Left (@ Sqlvalues, Len (@ sqlvalues)-4) + ') ''from' + @ tablename
Exec (@ SQL )

Publish by note

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.