I wrote a stored procedure some time ago to do this exact job. Although there is no technical column order in relationship theory, SSMS is not completely relational. The system stores the order in which the columns were inserted and assigns an identifier to them. This ordering is done using a typical SELECT * statement, so your SELECT statements seem to return the same order every time. In practice, there has never been a good idea to SELECT * with anything, since it does not block the order of the result in terms of columns or rows. However, I think that people are so obsessed with โthat you shouldn't do thisโ that they donโt write scripts that actually can do this. The fact is the predictable behavior of the system, so why not use it if the task is not very important.
This SPROC, of โโcourse, has reservations and is written in T-SQL, but if you just want to return all the values โโwith the same SELECT * behavior, this should make the job pretty easy for you. Enter a table name, number of columns and press F5. He returns them in order from left to right, just as you expected. I limited it to only 5 columns, but you can edit the logic if you need more. Accepts temporary and permanent tables.
EXEC OnlySomeColumns 'MyTable', 3
IF OBJECT_ID ('OnlySomeColumns', 'P') IS NOT NULL DROP PROCEDURE OnlySomeColumns; GO CREATE PROCEDURE OnlySomeColumns @TableName VARCHAR (1000), @TotalColumns INT AS DECLARE @Column1 VARCHAR (1000), @Column2 VARCHAR (1000), @Column3 VARCHAR (1000), @Column4 VARCHAR (1000), @Column5 VARCHAR (1000), @SQL VARCHAR (1000), @TempTable VARCHAR (1000), @PermanentTable VARCHAR (1000), @ColumnNamesAll VARCHAR (1000) --First determine if this is a temp table or permanent table IF @TableName LIKE '%#%' BEGIN SET @TempTable = @TableName END --If a temporary table IF @TableName NOT LIKE '%#%' BEGIN SET @PermanentTable = @TableName END --If a permanent column name SET NOCOUNT ON --Start with a few simple error checks IF ( @TempTable = 'NULL' AND @PermanentTable = 'NULL' ) BEGIN RAISERROR ( 'ERROR: Please select a TempTable or Permanent Table.',16,1 ) END IF ( @TempTable <> 'NULL' AND @PermanentTable <> 'NULL' ) BEGIN RAISERROR ( 'ERROR: Only one table can be selected at a time. Please adjust your table selection.',16,1 ) END IF ( @TotalColumns IS NULL ) BEGIN RAISERROR ( 'ERROR: Please select a value for @TotalColumns.',16,1 ) END --Temp table to gather the names of the columns IF Object_id('tempdb..#TempName') IS NOT NULL DROP TABLE
user2306008
source share