I have a stored procedure
alter PROCEDURE pricing.select_from_table @table_name NVARCHAR(255)
AS
begin
DECLARE @sql NVARCHAR(MAX);
SET @sql = N'SELECT * FROM ' + QUOTENAME(@table_name);
EXEC sp_executesql @sql;
END
and I run it through
EXECute [pricing].[select_from_table] 'pricing.pricingprod2023_nom3_copy2'
I get error Invalid object name 'pricing.pricingprod2023_nom3_copy2'.`
Even though table exists and I have permissions
I was trying to select all rows from a given database through sql stored procedure and I am expecting all the rows of the table name supplied
2条答案
按热度按时间3zwjbxry1#
QUOTENAME
is for each part, not the entire path.QUOTENAME(N'MySchema.MyTable')
results inN'[MySchema.MyTable]'
which when injected into a dynamic statement results in the object namedMySchema.MyTable
on theUSER
s default schema, such asdbo
:dbo.[MySchema.MyTable]
.If you need to provide both the schema and the object name, use 2 parameters:
7xzttuei2#
Something like this can be a better version:
It parses each table part and quotes it separately. I was a bit lazy to add linked server (parsename 4), but i have a feeling you should be able to figure it out if needed.
EDIT: Larnu's version that works from SQL Server 2017: