I'm genuinely curious and not the world's most well-versed in the inner workings of SQL. I apologize in advance if my terminology reflects my ignorance.
I've always been under the impression that using Stored Procedures in SQL allows for more efficient operation because the interpreter can predict the nature of the transaction and optimize it before it is called.
My question has to do with using dynamic table names in Stored Procedures, such as
USE [EODData]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Import_Correlation_CSV]
@fileURL varchar(500)
AS
BEGIN
SET NOCOUNT ON;
Declare @myTableSQL nvarchar(max);
SET @myTableSQL = 'BULK INSERT EOD_Stock_Correlations FROM '+@fileURL+' WITH ( FIELDTERMINATOR = '','',ROWTERMINATOR = ''\n'')'
exec sp_executesql @myTableSQL
end
GO
or
--Just the 'meat' this time:
Declare @ProductsSQL nvarchar(max);
SET @ProductsSQL = 'update ' + @table + ' set stats_completed = 0'
exec sp_executesql @ProductsSQL
Note: In each of the above references, @fileURL and/or @table are varchars used as input to the SP
It seems to me that, by use of a "dynamic table," the coder would lose the benefit of Stored Procedure as the SQL engine couldn't pre-interpret or predict the transaction. My own limited testing has shown nominal if any improvement in performance using this method over executing the SQL as a command rather than a SP.
Question(s) What are the specific benefits of using these "unpredictable" Stored Procedures instead of calling for execution of the SQL as a command (C#:NonQuery())? Do any benefits remain when calling a stored procedure that uses dynamic SQL? Essentially - is there any difference between calling a SP in this manner and using NonQuery()/Standard SQL command?
Mind you, I'm not necessarily asking which one is "better," or seeking opinions. I'm asking anyone who knows the inner workings of SQL what the specific advantages/disadvantages may be.
Thank you very much for your time and in advance for any insight or information you can provide.