Voglio impostare il nome della tabella in una query SQL dynamic. Ho provato con successo per parametro come segue:
/* Using sp_executesql */ /* Build and Execute a Transact-SQL String with a single parameter value Using sp_executesql Command */ /* Variable Declaration */ DECLARE @EmpID AS SMALLINT DECLARE @SQLQuery AS NVARCHAR(500) DECLARE @ParameterDefinition AS NVARCHAR(100) /* set the parameter value */ SET @EmpID = 1001 /* Build Transact-SQL String by including the parameter */ SET @SQLQuery = 'SELECT * FROM tblEmployees WHERE EmployeeID = @EmpID' /* Specify Parameter Format */ SET @ParameterDefinition = '@EmpID SMALLINT' /* Execute Transact-SQL String */ EXECUTE sp_executesql @SQLQuery, @ParameterDefinition, @EmpID
Ora voglio prendere TABLE NAME
dynamicmente usando un parametro, ma non sono riuscito a farlo. Per favore guidami.
I nomi delle tabelle non possono essere forniti come parametri, quindi dovrai build manualmente la stringa SQL in questo modo:
SET @SQLQuery = 'SELECT * FROM ' + @TableName + ' WHERE EmployeeID = @EmpID'
Tuttavia, assicurati che l’applicazione non consenta a un utente di inserire direttamente il valore di @TableName
, in quanto ciò renderebbe la tua query suscettibile all’iniezione SQL. Per una ansible soluzione a questo, vedere questa risposta .
Per evitare l’iniezione SQL, di solito cerco di utilizzare le funzioni ovunque sia ansible. In questo caso, puoi fare:
... SET @TableName = '<[db].><[schema].>tblEmployees' SET @TableID = OBJECT_ID(TableName) --won't resolve if malformsd/injected. ... SET @SQLQuery = 'SELECT * FROM ' + OBJECT_NAME(@TableID) + ' WHERE EmployeeID = @EmpID'
Prova questo:
/* Variable Declaration */ DECLARE @EmpID AS SMALLINT DECLARE @SQLQuery AS NVARCHAR(500) DECLARE @ParameterDefinition AS NVARCHAR(100) DECLARE @TableName AS NVARCHAR(100) /* set the parameter value */ SET @EmpID = 1001 SET @TableName = 'tblEmployees' /* Build Transact-SQL String by including the parameter */ SET @SQLQuery = 'SELECT * FROM ' + @TableName + ' WHERE EmployeeID = @EmpID' /* Specify Parameter Format */ SET @ParameterDefinition = '@EmpID SMALLINT' /* Execute Transact-SQL String */ EXECUTE sp_executesql @SQLQuery, @ParameterDefinition, @EmpID