-- Sqlserver query the strings composed of the common field names of two data tables through the cursor
-- Application Scenario: mostly include the current order data table and historical order data table, and query the association between the current valid user data table and historical deleted user data table. Most of the time, the fields in the current table are designed to be the same as those in the History table. If they are different, they will be used in the joint query of the two tables.
-- Define a data table name
Declare @ targettablename1 nvarchar (250) -- defines the name of the data table to be queried. Variable 1
Declare @ targettablename2 nvarchar (250) -- define the name of the data table to be queried variable 2
Set @ targettablename1 = 'data table name 1' -- change it to a in the name of the data table to be queried (A + B ).
Set @ targettablename2 = 'data table name 2' -- change it to B in the name of the data table to be queried (A + B ).
-- Define the total number of Columns
Declare @ totlecolumns int
Select @ totlecolumns = count (name) from syscolumns where id = object_id (@ targettablename1) and name in (Select name from syscolumns where id = object_id (@ targettablename2 ))
Print 'data table '+ @ targettablename1 +' and data table '+ @ targettablename2 +' total number of identical fields: '+ convert (nvarchar (20), @ totlecolumns)
-- Define all field name strings
Declare @ columnsstring nvarchar (4000) -- final result string variable
Set @ columnsstring =''
Declare @ columnname nvarchar (255) -- cursor storage variable
-- Read the common fields of the two tables through the cursor
-- Declare the cursor mycursor
Declare mycursor cursor for select name from syscolumns where id = object_id (@ targettablename1) and name in (Select name from syscolumns where id = object_id (@ targettablename2) Order by colid
-- Open the cursor
Open mycursor
-- Retrieve the data from the cursor and assign values to the variables 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 Start contains a comma
If left (@ columnsstring, 1) = ', 'set @ columnsstring = substring (@ columnsstring, 2, Len (@ columnsstring)-1)
Print @ columnsstring