Obtain the primary key in the MSSQL table (Stored Procedure)

Source: Internet
Author: User

Create a stored procedure and return the primary key of the table by passing in the table name parameter. The Stored Procedure Code is as follows:

 

Create proc pgetpkcolumn

(@ Tablename varchar (50 ))

As

/*

Create by leleyl

Obtain the auto-incrementing column of the data table to be imported.

*/

Declare @ columnname varchar (500)

Set @ columnname =''

Select @ columnname = @ columnname + ',' + C. Name

From

Sysindexes I,

Sysindexkeys K,

Sysobjects O,

Syscolumns C,

Policypes d

Where

I. name like 'pk _ %'

And O. ID = I. ID

And O. xtype = 'U'

And I. ID = K. ID

And I. indid = K. indid

And I. ID = O. ID

And I. ID = C. ID

And K. colid = C. colid

And I. indid> 0

And I. indid <255

And (I. Status & 64) = 0

And C. xtype = D. xtype

And O. Name = @ tablename

If charindex (',', @ columnname) = 1

Select stuff (@ columnname, 1, 1 ,'')

Else

Select @ columnname

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.