This article lists out the extensive list of scenarios in which we get the following error message and how to solve it.
Error Message:
Msg 128, Level 15, State 1, Line 1
The name “%.*s” is not permitted in this context. Valid expressions are constants, constant expressions, and (in some contexts) variables. Column names are not permitted.
Below are the couple of scenarios in which we come across this error and solution for it
Scenario 1: PRINT statement having table name or column name as it’s parameter
Try executing the below statement
DECLARE @AuthorName VARCHAR(100) = 'Basavaraj Biradar' PRINT AuthorName
RESULT:
Msg 128, Level 15, State 1, Line 2
The name “AuthorName” is not permitted in this context. Valid expressions are constants, constant expressions, and (in some contexts) variables. Column names are not permitted.
Reason for this error
In the above example, the variable AuthorName name is missing @ prefix symbol in the PRINT statement and resulting in this error message. Because of the missing @ prefix, Sql Server is interpreting it as Table Column name and which is not allowed in the PRINT statement.
Solution:
Let us correct the AuthorName variable’s missing @ prefix symbol in the PRINT statement and verify the result
DECLARE @AuthorName VARCHAR(100) = 'Basavaraj Biradar' PRINT @AuthorName
Scenario 2: DEFAULT value defined for the column is referring other columns of the table
Try executing the below create table statement
CREATE TABLE dbo.Orders (OrderId INT, Amount MONEY, Tax MONEY, Discount MONEY, Total MONEY DEFAULT (Amount + Tax + Discount))
RESULT:
Msg 128, Level 15, State 1, Line 3
The name “Amount” is not permitted in this context. Valid expressions are constants, constant expressions, and (in some contexts) variables. Column names are not permitted.
Reason for this error
The reason for this error is we are trying to use tables other columns as default value for a column which is not supported. Default value for the column can only be either a constant value or a scalar function or a NULL value.
Solution: One solution to this problem is, we can create Total as a computed column like below:
CREATE TABLE dbo.Orders (OrderId INT, Amount MONEY, Tax MONEY, Discount MONEY, Total AS (Amount + Tax + Discount))
Let me know if you have encountered this error in any other scenario.