I am trying to use the sp_rename
stored procedure with a variable since I do not have control over the source (an Excel file that changes the column name to have a date).
I drop a table, and then import that table. I then want to change the column name of that table so I used a schema query to find out what the column currently is so that I can change it with sp_rename
:
USE ESS
GO
DECLARE @TotalName NVARCHAR(255)
DECLARE @ColName NVARCHAR(255)
DECLARE @NewName NVARCHAR(255)
SELECT
@ColName = column_name
FROM
information_schema.columns
WHERE
TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'serverinv_unix_system_assignments_staging'
AND ordinal_position = 1;
SET @TotalName = CONCAT(N'dbo.serverinv_unix_system_assignements_staging.' ,@ColName)
SET @NewName = ''''+ @TotalName+ ''','''+''+'server_name'+''','''+'COLUMN'';'+''
-- Select @NewName
EXEC sp_rename @NewName
It works if I explicitly type it out like below.
USE ESS
GO
EXEC sp_rename 'dbo.serverinv_unix_system_assignments_staging.Hostname as of 8/26/2018','server_name','COLUMN';
GO
The error I get on the first code set is
Msg 201, Level 16, State 4, Procedure sp_rename, Line 0 [Batch Start Line 2]
Procedure or function 'sp_rename' expects parameter '@newname', which was not supplied.