I have this dilemma I am creating a procedure that uses a table from another database inside it. Say:
CREATE PROCEDURE uspRetrieveCurrentPropertyDate (
@InternalEntityId VARCHAR(10)
,@InternalUserId VARCHAR(10)
,@InternalSiteId VARCHAR(10) --this is the database I need to get the table from
)
as begin
...
...
select TOP 1 arsDailyCtlDate from @InternalSiteId..AccountsSetting
end
but of course it will return an error.
The original script uses something like:
SET @cSQL = 'SELECT TOP 1 arsDailyCtlDate FROM S' + @SiteID + '.dbo.AccountsSetting WITH (NOLOCK)'
EXEC(@cSQL)
to accomplish the task. But I wanted to rewrite the code. Is there anyway I can do it the way I like it to be done? Without using exec(@cSQL)?
Thanks, Sherwin
databasename.schemaname.tablenamein your dynamic sql? Also, usingsp_executesqlis recommended if you don't want to open doors for sql injection.sp_executesqlwon't protect from sql injection attacks here. Best option is to check the parameter against a white list before injecting the database name in to the dynamic sql.