SQL returns the name of all fields in a specified data table.

Source: Internet
Author: User

-- In view of the fact that the field name is often required to obtain the list data of a data table. The following code is compiled.

-- Applicable scenarios: design or update select statements or insert statements for SQL stored procedures

-- The returned string format is similar to: "ID, begintime, endtime, addip, updateuser, updatetime, updateip"

 

-- Select name from syscolumns where id = object_id ('data table name ')
-- Define a data table name
Declare @ targettablename nvarchar (250)

Set @ targettablename = 'data table name'
-- Define the total number of Columns
Declare @ totlecolumns int
Select @ totlecolumns = count (*) from syscolumns where id = object_id (@ targettablename)
-- Print @ totlecolumns
-- Select * From syscolumns where id = object_id (@ targettablename)
-- Define all field name strings
Declare @ columnsstring nvarchar (4000)
Declare @ tempname nvarchar (4000)
Set @ columnsstring =''
Set @ tempname =''
Declare @ I int
Set @ I = 1
While @ I <= @ totlecolumns
Begin
-- Print @ I
Select @ tempname = Name from syscolumns where id = object_id (@ targettablename) and colorder = @ I

Set @ columnsstring = @ columnsstring + ',' + @ tempname
Set @ I = @ I + 1
End

If left (@ columnsstring, 1) = ', 'set @ columnsstring = substring (@ columnsstring, 2, Len (@ columnsstring)-1)

Print @ columnsstring

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.