-- SQL Server queries string scripts composed of all fields in a single data table
-- Application: used to generate select field Name List 1 from Table group by field Name List 2 and field Name List 2 in the SQL query string
-- Define the data table name variable
Declare @ tablename nvarchar (250)
Set @ tablename = 'your data table name' -- change the name of the data table to be queried.
-- Defines the total number of columns variable
Declare @ totalcolumns int
Select @ totalcolumns = count (name) from syscolumns where id = object_id (@ tablename)
Print 'data table '+ @ tablename +': '+ convert (nvarchar (20), @ totalcolumns)
-- Define all field names string variables
Declare @ columnsstring nvarchar (4000)
Set @ columnsstring =''
-- Define the field name variable output in the cursor
Declare @ columnname nvarchar (255)
-- Read all fields of a specified data table through a cursor
-- Declare the cursor mycursor
Declare mycursor cursor for select name from syscolumns where id = object_id (@ tablename) order by colid
-- Open the cursor
Open mycursor
-- Retrieve the data from the cursor and assign values to the field name variable we just declared.
Fetch next from mycursor into @ columnname
-- If the cursor is successfully executed
While (@ fetch_status = 0)
Begin
-- Display the value we retrieve with the cursor each time
Set @ columnsstring = @ columnsstring + ',' + @ columnname
-- Use a cursor to retrieve the next record
Fetch next from mycursor into @ columnname
End
-- Close the cursor
Close mycursor
-- Undo cursor
Deallocate mycursor
-- Remove if the end contains a comma
If left (@ columnsstring, 1) = ', 'set @ columnsstring = substring (@ columnsstring, 2, Len (@ columnsstring)-1)
Print @ columnsstring
-- Multi-table joint Query
Declare @ groupcolumnsstring nvarchar (4000) -- if the display is incomplete, modify a larger number here.
Declare @ prefixstring nvarchar (255)
Set @ prefixstring = @ tablename -- here you can change it to the string you want
Set @ groupcolumnsstring = Replace (@ columnsstring, '+ @ prefixstring + '.')
Set @ groupcolumnsstring = @ prefixstring + '.' + @ groupcolumnsstring
Print @ groupcolumnsstring