Sample Header Ad - 728x90

Alter table - add a new column as the first column in the table - sql server

0 votes
3 answers
138 views
Before doing a restore of a database I check how much space I have in each drive on the destination server. I use this script:
IF OBJECT_ID ('tempdb..#FREE_SPACE_DRIVES','u') IS NOT NULL
BEGIN
DROP TABLE #FREE_SPACE_DRIVES;
END


CREATE TABLE #FREE_SPACE_DRIVES(
DRIVE CHAR(1)PRIMARY KEY,
FREESPACE BIGINT NOT NULL
)

INSERT INTO #FREE_SPACE_DRIVES
EXECUTE master.dbo.xp_fixeddrives;
then to see what are the available disk space I use the following query:
select d.DRIVE  
      ,[DriveFreeSpace(GB)] =   REPLACE(CONVERT(VARCHAR(50),CAST(    CAST(d.FREESPACE/1024.00 as DECIMAL(12,2))     AS MONEY),1), '.00','')
from  #FREE_SPACE_DRIVES D with(nolock)
and that gives me: enter image description here that is all good, but now I want the servername shown on the picture as well. ok I can add @@servername to my script and it will show the servername too.
select [Server Name] = 'DBA Paradise' --@@servername 
      ,d.DRIVE  
      ,[DriveFreeSpace(GB)] =   REPLACE(CONVERT(VARCHAR(50),CAST(    CAST(d.FREESPACE/1024.00 as DECIMAL(12,2))     AS MONEY),1), '.00','')
from  #FREE_SPACE_DRIVES D with(nolock)
enter image description here My question is actually about alter table. when I do this alter table:
ALTER TABLE #FREE_SPACE_DRIVES
add  server_name nvarchar(128) not null default (@@servername)
when I run this select:
select * from  #FREE_SPACE_DRIVES
I get: enter image description here that is all good, but I need the new column to be the first in my table, is there a way to get this done? then the result would be > server_name, drive, freespace
Asked by Marcello Miorelli (17274 rep)
Jul 3, 2024, 10:29 AM
Last activity: Aug 3, 2024, 06:56 AM