How to get the name of the database a stored procedure is executed in within that stored procedure while it's executing?How to make a flexible service broker receive in a stored sql procedure, how to pass “FROM” parameter into receiveHow to log within a stored procedure that is encapsulated within a transactionHow to use same stored procedure for different tables and avoid using dynamic sqlSSRS - ERROR NUMBER:7357 while passing multiple value parameters using comma delimited string to stored procedureHow to write stored procedure use SP_HELPTEXT for getting information of objects belong to another databaseWhy always throwing error “Must declare scalar variable” while executing stored procedure?Multiple disparate functions within stored procedureHow properly call stored procedure from EXEC(SQL)?Stored Procedure Asking for Input While Processinghow to add option(recompile) within this stored procedure?

How to answer questions about my characters?

Why doesn't the EU now just force the UK to choose between referendum and no-deal?

Possible Leak In Concrete

Why must traveling waves have the same amplitude to form a standing wave?

I need to drive a 7/16" nut but am unsure how to use the socket I bought for my screwdriver

Is it true that real estate prices mainly go up?

Why did it take so long to abandon sail after steamships were demonstrated?

Life insurance that covers only simultaneous/dual deaths

How do anti-virus programs start at Windows boot?

How to generate globally unique ids for different tables of the same database?

How to explain that I do not want to visit a country due to personal safety concern?

Why is stat::st_size 0 for devices but at the same time lseek defines the device size correctly?

Bash: What does "masking return values" mean?

Humanity loses the vast majority of its technology, information, and population in the year 2122. How long does it take to rebuild itself?

Happy pi day, everyone!

Where is the 1/8 CR apprentice in Volo's Guide to Monsters?

SQL Server Primary Login Restrictions

Could the Saturn V actually have launched astronauts around Venus?

Is having access to past exams cheating and, if yes, could it be proven just by a good grade?

Why are the outputs of printf and std::cout different

How to make healing in an exploration game interesting

How to deal with taxi scam when on vacation?

Is a lawful good "antagonist" effective?

Good allowance savings plan?



How to get the name of the database a stored procedure is executed in within that stored procedure while it's executing?


How to make a flexible service broker receive in a stored sql procedure, how to pass “FROM” parameter into receiveHow to log within a stored procedure that is encapsulated within a transactionHow to use same stored procedure for different tables and avoid using dynamic sqlSSRS - ERROR NUMBER:7357 while passing multiple value parameters using comma delimited string to stored procedureHow to write stored procedure use SP_HELPTEXT for getting information of objects belong to another databaseWhy always throwing error “Must declare scalar variable” while executing stored procedure?Multiple disparate functions within stored procedureHow properly call stored procedure from EXEC(SQL)?Stored Procedure Asking for Input While Processinghow to add option(recompile) within this stored procedure?













2















Weird question?...maybe, but I have a need. :)



I have a stored procedure that I want to use universally in any database.
The stored procedure generates some dynamic SQL and then executes that SQL in a database that is passed in as one of the parameters in this procedure.



BUT I want to make the database parameter optional and when no database name is passed in, I want the dynamic SQL to execute within the same database that the procedure itself was called from. (Please keep in mind this procedure could be executed across databases and not within the same database that the procedure itself lives in.)










share|improve this question






















  • Do you need dynamic SQL? Is something stopping you from doing like: IF @dbname IS NULL then @dbname = (SELECT dbname()) or you mean the calling procedure itself?

    – Jacob H
    5 hours ago






  • 1





    @JacobH that unfortunately does not work when calling a stored proc from a different database, as it returns the dbname where the stored proc resides in.

    – Randi Vertongen
    5 hours ago












  • Right, I want when the procedure executes, a way for the procedure to be able to determine which database the query that executed it was executed from. For example if my procedure lives in database A, and I execute it from database B, then I want the procedure that lives in database A to be able to determine the query that executed it came from database B.

    – J.D.
    4 hours ago















2















Weird question?...maybe, but I have a need. :)



I have a stored procedure that I want to use universally in any database.
The stored procedure generates some dynamic SQL and then executes that SQL in a database that is passed in as one of the parameters in this procedure.



BUT I want to make the database parameter optional and when no database name is passed in, I want the dynamic SQL to execute within the same database that the procedure itself was called from. (Please keep in mind this procedure could be executed across databases and not within the same database that the procedure itself lives in.)










share|improve this question






















  • Do you need dynamic SQL? Is something stopping you from doing like: IF @dbname IS NULL then @dbname = (SELECT dbname()) or you mean the calling procedure itself?

    – Jacob H
    5 hours ago






  • 1





    @JacobH that unfortunately does not work when calling a stored proc from a different database, as it returns the dbname where the stored proc resides in.

    – Randi Vertongen
    5 hours ago












  • Right, I want when the procedure executes, a way for the procedure to be able to determine which database the query that executed it was executed from. For example if my procedure lives in database A, and I execute it from database B, then I want the procedure that lives in database A to be able to determine the query that executed it came from database B.

    – J.D.
    4 hours ago













2












2








2








Weird question?...maybe, but I have a need. :)



I have a stored procedure that I want to use universally in any database.
The stored procedure generates some dynamic SQL and then executes that SQL in a database that is passed in as one of the parameters in this procedure.



BUT I want to make the database parameter optional and when no database name is passed in, I want the dynamic SQL to execute within the same database that the procedure itself was called from. (Please keep in mind this procedure could be executed across databases and not within the same database that the procedure itself lives in.)










share|improve this question














Weird question?...maybe, but I have a need. :)



I have a stored procedure that I want to use universally in any database.
The stored procedure generates some dynamic SQL and then executes that SQL in a database that is passed in as one of the parameters in this procedure.



BUT I want to make the database parameter optional and when no database name is passed in, I want the dynamic SQL to execute within the same database that the procedure itself was called from. (Please keep in mind this procedure could be executed across databases and not within the same database that the procedure itself lives in.)







sql-server sql-server-2008-r2 stored-procedures dynamic-sql






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked 6 hours ago









J.D.J.D.

512312




512312












  • Do you need dynamic SQL? Is something stopping you from doing like: IF @dbname IS NULL then @dbname = (SELECT dbname()) or you mean the calling procedure itself?

    – Jacob H
    5 hours ago






  • 1





    @JacobH that unfortunately does not work when calling a stored proc from a different database, as it returns the dbname where the stored proc resides in.

    – Randi Vertongen
    5 hours ago












  • Right, I want when the procedure executes, a way for the procedure to be able to determine which database the query that executed it was executed from. For example if my procedure lives in database A, and I execute it from database B, then I want the procedure that lives in database A to be able to determine the query that executed it came from database B.

    – J.D.
    4 hours ago

















  • Do you need dynamic SQL? Is something stopping you from doing like: IF @dbname IS NULL then @dbname = (SELECT dbname()) or you mean the calling procedure itself?

    – Jacob H
    5 hours ago






  • 1





    @JacobH that unfortunately does not work when calling a stored proc from a different database, as it returns the dbname where the stored proc resides in.

    – Randi Vertongen
    5 hours ago












  • Right, I want when the procedure executes, a way for the procedure to be able to determine which database the query that executed it was executed from. For example if my procedure lives in database A, and I execute it from database B, then I want the procedure that lives in database A to be able to determine the query that executed it came from database B.

    – J.D.
    4 hours ago
















Do you need dynamic SQL? Is something stopping you from doing like: IF @dbname IS NULL then @dbname = (SELECT dbname()) or you mean the calling procedure itself?

– Jacob H
5 hours ago





Do you need dynamic SQL? Is something stopping you from doing like: IF @dbname IS NULL then @dbname = (SELECT dbname()) or you mean the calling procedure itself?

– Jacob H
5 hours ago




1




1





@JacobH that unfortunately does not work when calling a stored proc from a different database, as it returns the dbname where the stored proc resides in.

– Randi Vertongen
5 hours ago






@JacobH that unfortunately does not work when calling a stored proc from a different database, as it returns the dbname where the stored proc resides in.

– Randi Vertongen
5 hours ago














Right, I want when the procedure executes, a way for the procedure to be able to determine which database the query that executed it was executed from. For example if my procedure lives in database A, and I execute it from database B, then I want the procedure that lives in database A to be able to determine the query that executed it came from database B.

– J.D.
4 hours ago





Right, I want when the procedure executes, a way for the procedure to be able to determine which database the query that executed it was executed from. For example if my procedure lives in database A, and I execute it from database B, then I want the procedure that lives in database A to be able to determine the query that executed it came from database B.

– J.D.
4 hours ago










3 Answers
3






active

oldest

votes


















4














You can easily tell the dynamic SQL execute in a specific database by dynamically building a [database].sys.sp_executesql command:



USE your_database;
GO

CREATE PROCEDURE dbo.DatabaseNameOptional
@db sysname = NULL
AS
BEGIN
SET NOCOUNT ON;

DECLARE @sql nvarchar(max) = N'SELECT DB_NAME(); /* other stuff */'

DECLARE @exec nvarchar(770) = COALESCE(@db, DB_NAME())
+ N'.sys.sp_executesql';

-- alternatively, just leave DB_NAME() out of it:

--DECLARE @exec nvarchar(770) = COALESCE(@db, N'')
-- + N'sys.sp_executesql';

EXEC @exec @sql;
END
GO


Try it out:



USE your_database;
GO

EXEC dbo.DatabaseNameOptional;
GO -- output = your_database

EXEC dbo.DatabaseNameOptional @db = N'master';
GO -- output = master

USE tempdb;
GO

EXEC your_database.dbo.DatabaseNameOptional;
GO -- output = your_database

EXEC your_database.dbo.DatabaseNameOptional @db = N'master';
GO -- output = master


In the execution context of the procedure, though, no, I don't think there's any way to determine where the call originated from (or to run in that context). That's the benefit of using a system-marked procedure in master - if that's the functionality you want, you need to decide if "putting objects in master" is ickier than "not getting what I want."






share|improve this answer

























  • Thanks! I'm good on building / executing the dynamic SQL end, but I'm sad there isn't a better way to determine the database which the stored procedure query was executed from. Perhaps it would be pretty janky, but what about going by one of the tables or DMVs that cache query execution stats? (I guess you would need to know the user who executed it too to not mix up concurrent executions.)

    – J.D.
    2 hours ago



















1














I don't like creating procedures in master, but if you put your procedure in the master database and add the SP_ prefix like sp_dynamicproc, you could call it from inside your own user database and get the correct db_name() parameter.



Source



An example



USE master 
GO
CREATE PROCEDURE dbo.sp_dynamicproc
(@dbname nvarchar(255) = NULL)
as
BEGIN

DECLARE @SQL NVARCHAR(MAX)

IF @dbname IS NULL
BEGIN
SET @dbname = (SELECT db_name());
END
SELECT db_name()
SET @SQL = 'SELECT * FROM '+QUOTENAME(@dbname)+'.INFORMATION_SCHEMA.COLUMNS ;';
EXEC(@SQL);

END


Calling the proc



USE test
GO
exec dbo.sp_dynamicproc;


Result



enter image description here






share|improve this answer

























  • Cool, this is helpful, +1 for that. But I'm with ya, I'd prefer to not create objects in the master database, and I have a dedicated database this procedure lives in with other similar types of functions.

    – J.D.
    4 hours ago


















0














Why don't you create your own SQL Server System Stored Procedures?



It's a better solution than using dynamic SQL.






share|improve this answer























  • Dynamic SQL will be occurring regardless, because I need to change my SQL statements that are executed based on the parameters inputted into the procedure. I gave you the +1 though because your answer is similarly helpful as @Randi's but I'd prefer to not create objects in the master database.

    – J.D.
    4 hours ago






  • 1





    Why is dynamic SQL bad? It's like a lot of things - it can be dangerous in certain scenarios, if you choose to use it without any research, but it shouldn't be written off just as a matter of course. It can accomplish a lot of really powerful things that you wouldn't be able to do otherwise.

    – Aaron Bertrand
    2 hours ago












  • Agreed, but I'm not saying dynamic SQL is bad. It's really powerful and I do like it actually. I use it in my favor to improve performance in difference situations, and to do whatever I need to customize some routines. When I first suggested, it seemed that it would be a "static stored procedure" or something like that. Using System Stored procedures he would be able to run something like: EXEC DB1.dbo.SP_whatever , EXEC DB2.dbo.SP_whatever. It would be pretty easy to know from which database it comes from.

    – Dan
    1 hour ago










Your Answer








StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "182"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f232169%2fhow-to-get-the-name-of-the-database-a-stored-procedure-is-executed-in-within-tha%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























3 Answers
3






active

oldest

votes








3 Answers
3






active

oldest

votes









active

oldest

votes






active

oldest

votes









4














You can easily tell the dynamic SQL execute in a specific database by dynamically building a [database].sys.sp_executesql command:



USE your_database;
GO

CREATE PROCEDURE dbo.DatabaseNameOptional
@db sysname = NULL
AS
BEGIN
SET NOCOUNT ON;

DECLARE @sql nvarchar(max) = N'SELECT DB_NAME(); /* other stuff */'

DECLARE @exec nvarchar(770) = COALESCE(@db, DB_NAME())
+ N'.sys.sp_executesql';

-- alternatively, just leave DB_NAME() out of it:

--DECLARE @exec nvarchar(770) = COALESCE(@db, N'')
-- + N'sys.sp_executesql';

EXEC @exec @sql;
END
GO


Try it out:



USE your_database;
GO

EXEC dbo.DatabaseNameOptional;
GO -- output = your_database

EXEC dbo.DatabaseNameOptional @db = N'master';
GO -- output = master

USE tempdb;
GO

EXEC your_database.dbo.DatabaseNameOptional;
GO -- output = your_database

EXEC your_database.dbo.DatabaseNameOptional @db = N'master';
GO -- output = master


In the execution context of the procedure, though, no, I don't think there's any way to determine where the call originated from (or to run in that context). That's the benefit of using a system-marked procedure in master - if that's the functionality you want, you need to decide if "putting objects in master" is ickier than "not getting what I want."






share|improve this answer

























  • Thanks! I'm good on building / executing the dynamic SQL end, but I'm sad there isn't a better way to determine the database which the stored procedure query was executed from. Perhaps it would be pretty janky, but what about going by one of the tables or DMVs that cache query execution stats? (I guess you would need to know the user who executed it too to not mix up concurrent executions.)

    – J.D.
    2 hours ago
















4














You can easily tell the dynamic SQL execute in a specific database by dynamically building a [database].sys.sp_executesql command:



USE your_database;
GO

CREATE PROCEDURE dbo.DatabaseNameOptional
@db sysname = NULL
AS
BEGIN
SET NOCOUNT ON;

DECLARE @sql nvarchar(max) = N'SELECT DB_NAME(); /* other stuff */'

DECLARE @exec nvarchar(770) = COALESCE(@db, DB_NAME())
+ N'.sys.sp_executesql';

-- alternatively, just leave DB_NAME() out of it:

--DECLARE @exec nvarchar(770) = COALESCE(@db, N'')
-- + N'sys.sp_executesql';

EXEC @exec @sql;
END
GO


Try it out:



USE your_database;
GO

EXEC dbo.DatabaseNameOptional;
GO -- output = your_database

EXEC dbo.DatabaseNameOptional @db = N'master';
GO -- output = master

USE tempdb;
GO

EXEC your_database.dbo.DatabaseNameOptional;
GO -- output = your_database

EXEC your_database.dbo.DatabaseNameOptional @db = N'master';
GO -- output = master


In the execution context of the procedure, though, no, I don't think there's any way to determine where the call originated from (or to run in that context). That's the benefit of using a system-marked procedure in master - if that's the functionality you want, you need to decide if "putting objects in master" is ickier than "not getting what I want."






share|improve this answer

























  • Thanks! I'm good on building / executing the dynamic SQL end, but I'm sad there isn't a better way to determine the database which the stored procedure query was executed from. Perhaps it would be pretty janky, but what about going by one of the tables or DMVs that cache query execution stats? (I guess you would need to know the user who executed it too to not mix up concurrent executions.)

    – J.D.
    2 hours ago














4












4








4







You can easily tell the dynamic SQL execute in a specific database by dynamically building a [database].sys.sp_executesql command:



USE your_database;
GO

CREATE PROCEDURE dbo.DatabaseNameOptional
@db sysname = NULL
AS
BEGIN
SET NOCOUNT ON;

DECLARE @sql nvarchar(max) = N'SELECT DB_NAME(); /* other stuff */'

DECLARE @exec nvarchar(770) = COALESCE(@db, DB_NAME())
+ N'.sys.sp_executesql';

-- alternatively, just leave DB_NAME() out of it:

--DECLARE @exec nvarchar(770) = COALESCE(@db, N'')
-- + N'sys.sp_executesql';

EXEC @exec @sql;
END
GO


Try it out:



USE your_database;
GO

EXEC dbo.DatabaseNameOptional;
GO -- output = your_database

EXEC dbo.DatabaseNameOptional @db = N'master';
GO -- output = master

USE tempdb;
GO

EXEC your_database.dbo.DatabaseNameOptional;
GO -- output = your_database

EXEC your_database.dbo.DatabaseNameOptional @db = N'master';
GO -- output = master


In the execution context of the procedure, though, no, I don't think there's any way to determine where the call originated from (or to run in that context). That's the benefit of using a system-marked procedure in master - if that's the functionality you want, you need to decide if "putting objects in master" is ickier than "not getting what I want."






share|improve this answer















You can easily tell the dynamic SQL execute in a specific database by dynamically building a [database].sys.sp_executesql command:



USE your_database;
GO

CREATE PROCEDURE dbo.DatabaseNameOptional
@db sysname = NULL
AS
BEGIN
SET NOCOUNT ON;

DECLARE @sql nvarchar(max) = N'SELECT DB_NAME(); /* other stuff */'

DECLARE @exec nvarchar(770) = COALESCE(@db, DB_NAME())
+ N'.sys.sp_executesql';

-- alternatively, just leave DB_NAME() out of it:

--DECLARE @exec nvarchar(770) = COALESCE(@db, N'')
-- + N'sys.sp_executesql';

EXEC @exec @sql;
END
GO


Try it out:



USE your_database;
GO

EXEC dbo.DatabaseNameOptional;
GO -- output = your_database

EXEC dbo.DatabaseNameOptional @db = N'master';
GO -- output = master

USE tempdb;
GO

EXEC your_database.dbo.DatabaseNameOptional;
GO -- output = your_database

EXEC your_database.dbo.DatabaseNameOptional @db = N'master';
GO -- output = master


In the execution context of the procedure, though, no, I don't think there's any way to determine where the call originated from (or to run in that context). That's the benefit of using a system-marked procedure in master - if that's the functionality you want, you need to decide if "putting objects in master" is ickier than "not getting what I want."







share|improve this answer














share|improve this answer



share|improve this answer








edited 2 hours ago

























answered 3 hours ago









Aaron BertrandAaron Bertrand

152k18294490




152k18294490












  • Thanks! I'm good on building / executing the dynamic SQL end, but I'm sad there isn't a better way to determine the database which the stored procedure query was executed from. Perhaps it would be pretty janky, but what about going by one of the tables or DMVs that cache query execution stats? (I guess you would need to know the user who executed it too to not mix up concurrent executions.)

    – J.D.
    2 hours ago


















  • Thanks! I'm good on building / executing the dynamic SQL end, but I'm sad there isn't a better way to determine the database which the stored procedure query was executed from. Perhaps it would be pretty janky, but what about going by one of the tables or DMVs that cache query execution stats? (I guess you would need to know the user who executed it too to not mix up concurrent executions.)

    – J.D.
    2 hours ago

















Thanks! I'm good on building / executing the dynamic SQL end, but I'm sad there isn't a better way to determine the database which the stored procedure query was executed from. Perhaps it would be pretty janky, but what about going by one of the tables or DMVs that cache query execution stats? (I guess you would need to know the user who executed it too to not mix up concurrent executions.)

– J.D.
2 hours ago






Thanks! I'm good on building / executing the dynamic SQL end, but I'm sad there isn't a better way to determine the database which the stored procedure query was executed from. Perhaps it would be pretty janky, but what about going by one of the tables or DMVs that cache query execution stats? (I guess you would need to know the user who executed it too to not mix up concurrent executions.)

– J.D.
2 hours ago














1














I don't like creating procedures in master, but if you put your procedure in the master database and add the SP_ prefix like sp_dynamicproc, you could call it from inside your own user database and get the correct db_name() parameter.



Source



An example



USE master 
GO
CREATE PROCEDURE dbo.sp_dynamicproc
(@dbname nvarchar(255) = NULL)
as
BEGIN

DECLARE @SQL NVARCHAR(MAX)

IF @dbname IS NULL
BEGIN
SET @dbname = (SELECT db_name());
END
SELECT db_name()
SET @SQL = 'SELECT * FROM '+QUOTENAME(@dbname)+'.INFORMATION_SCHEMA.COLUMNS ;';
EXEC(@SQL);

END


Calling the proc



USE test
GO
exec dbo.sp_dynamicproc;


Result



enter image description here






share|improve this answer

























  • Cool, this is helpful, +1 for that. But I'm with ya, I'd prefer to not create objects in the master database, and I have a dedicated database this procedure lives in with other similar types of functions.

    – J.D.
    4 hours ago















1














I don't like creating procedures in master, but if you put your procedure in the master database and add the SP_ prefix like sp_dynamicproc, you could call it from inside your own user database and get the correct db_name() parameter.



Source



An example



USE master 
GO
CREATE PROCEDURE dbo.sp_dynamicproc
(@dbname nvarchar(255) = NULL)
as
BEGIN

DECLARE @SQL NVARCHAR(MAX)

IF @dbname IS NULL
BEGIN
SET @dbname = (SELECT db_name());
END
SELECT db_name()
SET @SQL = 'SELECT * FROM '+QUOTENAME(@dbname)+'.INFORMATION_SCHEMA.COLUMNS ;';
EXEC(@SQL);

END


Calling the proc



USE test
GO
exec dbo.sp_dynamicproc;


Result



enter image description here






share|improve this answer

























  • Cool, this is helpful, +1 for that. But I'm with ya, I'd prefer to not create objects in the master database, and I have a dedicated database this procedure lives in with other similar types of functions.

    – J.D.
    4 hours ago













1












1








1







I don't like creating procedures in master, but if you put your procedure in the master database and add the SP_ prefix like sp_dynamicproc, you could call it from inside your own user database and get the correct db_name() parameter.



Source



An example



USE master 
GO
CREATE PROCEDURE dbo.sp_dynamicproc
(@dbname nvarchar(255) = NULL)
as
BEGIN

DECLARE @SQL NVARCHAR(MAX)

IF @dbname IS NULL
BEGIN
SET @dbname = (SELECT db_name());
END
SELECT db_name()
SET @SQL = 'SELECT * FROM '+QUOTENAME(@dbname)+'.INFORMATION_SCHEMA.COLUMNS ;';
EXEC(@SQL);

END


Calling the proc



USE test
GO
exec dbo.sp_dynamicproc;


Result



enter image description here






share|improve this answer















I don't like creating procedures in master, but if you put your procedure in the master database and add the SP_ prefix like sp_dynamicproc, you could call it from inside your own user database and get the correct db_name() parameter.



Source



An example



USE master 
GO
CREATE PROCEDURE dbo.sp_dynamicproc
(@dbname nvarchar(255) = NULL)
as
BEGIN

DECLARE @SQL NVARCHAR(MAX)

IF @dbname IS NULL
BEGIN
SET @dbname = (SELECT db_name());
END
SELECT db_name()
SET @SQL = 'SELECT * FROM '+QUOTENAME(@dbname)+'.INFORMATION_SCHEMA.COLUMNS ;';
EXEC(@SQL);

END


Calling the proc



USE test
GO
exec dbo.sp_dynamicproc;


Result



enter image description here







share|improve this answer














share|improve this answer



share|improve this answer








edited 5 hours ago

























answered 5 hours ago









Randi VertongenRandi Vertongen

3,569822




3,569822












  • Cool, this is helpful, +1 for that. But I'm with ya, I'd prefer to not create objects in the master database, and I have a dedicated database this procedure lives in with other similar types of functions.

    – J.D.
    4 hours ago

















  • Cool, this is helpful, +1 for that. But I'm with ya, I'd prefer to not create objects in the master database, and I have a dedicated database this procedure lives in with other similar types of functions.

    – J.D.
    4 hours ago
















Cool, this is helpful, +1 for that. But I'm with ya, I'd prefer to not create objects in the master database, and I have a dedicated database this procedure lives in with other similar types of functions.

– J.D.
4 hours ago





Cool, this is helpful, +1 for that. But I'm with ya, I'd prefer to not create objects in the master database, and I have a dedicated database this procedure lives in with other similar types of functions.

– J.D.
4 hours ago











0














Why don't you create your own SQL Server System Stored Procedures?



It's a better solution than using dynamic SQL.






share|improve this answer























  • Dynamic SQL will be occurring regardless, because I need to change my SQL statements that are executed based on the parameters inputted into the procedure. I gave you the +1 though because your answer is similarly helpful as @Randi's but I'd prefer to not create objects in the master database.

    – J.D.
    4 hours ago






  • 1





    Why is dynamic SQL bad? It's like a lot of things - it can be dangerous in certain scenarios, if you choose to use it without any research, but it shouldn't be written off just as a matter of course. It can accomplish a lot of really powerful things that you wouldn't be able to do otherwise.

    – Aaron Bertrand
    2 hours ago












  • Agreed, but I'm not saying dynamic SQL is bad. It's really powerful and I do like it actually. I use it in my favor to improve performance in difference situations, and to do whatever I need to customize some routines. When I first suggested, it seemed that it would be a "static stored procedure" or something like that. Using System Stored procedures he would be able to run something like: EXEC DB1.dbo.SP_whatever , EXEC DB2.dbo.SP_whatever. It would be pretty easy to know from which database it comes from.

    – Dan
    1 hour ago















0














Why don't you create your own SQL Server System Stored Procedures?



It's a better solution than using dynamic SQL.






share|improve this answer























  • Dynamic SQL will be occurring regardless, because I need to change my SQL statements that are executed based on the parameters inputted into the procedure. I gave you the +1 though because your answer is similarly helpful as @Randi's but I'd prefer to not create objects in the master database.

    – J.D.
    4 hours ago






  • 1





    Why is dynamic SQL bad? It's like a lot of things - it can be dangerous in certain scenarios, if you choose to use it without any research, but it shouldn't be written off just as a matter of course. It can accomplish a lot of really powerful things that you wouldn't be able to do otherwise.

    – Aaron Bertrand
    2 hours ago












  • Agreed, but I'm not saying dynamic SQL is bad. It's really powerful and I do like it actually. I use it in my favor to improve performance in difference situations, and to do whatever I need to customize some routines. When I first suggested, it seemed that it would be a "static stored procedure" or something like that. Using System Stored procedures he would be able to run something like: EXEC DB1.dbo.SP_whatever , EXEC DB2.dbo.SP_whatever. It would be pretty easy to know from which database it comes from.

    – Dan
    1 hour ago













0












0








0







Why don't you create your own SQL Server System Stored Procedures?



It's a better solution than using dynamic SQL.






share|improve this answer













Why don't you create your own SQL Server System Stored Procedures?



It's a better solution than using dynamic SQL.







share|improve this answer












share|improve this answer



share|improve this answer










answered 5 hours ago









DanDan

644416




644416












  • Dynamic SQL will be occurring regardless, because I need to change my SQL statements that are executed based on the parameters inputted into the procedure. I gave you the +1 though because your answer is similarly helpful as @Randi's but I'd prefer to not create objects in the master database.

    – J.D.
    4 hours ago






  • 1





    Why is dynamic SQL bad? It's like a lot of things - it can be dangerous in certain scenarios, if you choose to use it without any research, but it shouldn't be written off just as a matter of course. It can accomplish a lot of really powerful things that you wouldn't be able to do otherwise.

    – Aaron Bertrand
    2 hours ago












  • Agreed, but I'm not saying dynamic SQL is bad. It's really powerful and I do like it actually. I use it in my favor to improve performance in difference situations, and to do whatever I need to customize some routines. When I first suggested, it seemed that it would be a "static stored procedure" or something like that. Using System Stored procedures he would be able to run something like: EXEC DB1.dbo.SP_whatever , EXEC DB2.dbo.SP_whatever. It would be pretty easy to know from which database it comes from.

    – Dan
    1 hour ago

















  • Dynamic SQL will be occurring regardless, because I need to change my SQL statements that are executed based on the parameters inputted into the procedure. I gave you the +1 though because your answer is similarly helpful as @Randi's but I'd prefer to not create objects in the master database.

    – J.D.
    4 hours ago






  • 1





    Why is dynamic SQL bad? It's like a lot of things - it can be dangerous in certain scenarios, if you choose to use it without any research, but it shouldn't be written off just as a matter of course. It can accomplish a lot of really powerful things that you wouldn't be able to do otherwise.

    – Aaron Bertrand
    2 hours ago












  • Agreed, but I'm not saying dynamic SQL is bad. It's really powerful and I do like it actually. I use it in my favor to improve performance in difference situations, and to do whatever I need to customize some routines. When I first suggested, it seemed that it would be a "static stored procedure" or something like that. Using System Stored procedures he would be able to run something like: EXEC DB1.dbo.SP_whatever , EXEC DB2.dbo.SP_whatever. It would be pretty easy to know from which database it comes from.

    – Dan
    1 hour ago
















Dynamic SQL will be occurring regardless, because I need to change my SQL statements that are executed based on the parameters inputted into the procedure. I gave you the +1 though because your answer is similarly helpful as @Randi's but I'd prefer to not create objects in the master database.

– J.D.
4 hours ago





Dynamic SQL will be occurring regardless, because I need to change my SQL statements that are executed based on the parameters inputted into the procedure. I gave you the +1 though because your answer is similarly helpful as @Randi's but I'd prefer to not create objects in the master database.

– J.D.
4 hours ago




1




1





Why is dynamic SQL bad? It's like a lot of things - it can be dangerous in certain scenarios, if you choose to use it without any research, but it shouldn't be written off just as a matter of course. It can accomplish a lot of really powerful things that you wouldn't be able to do otherwise.

– Aaron Bertrand
2 hours ago






Why is dynamic SQL bad? It's like a lot of things - it can be dangerous in certain scenarios, if you choose to use it without any research, but it shouldn't be written off just as a matter of course. It can accomplish a lot of really powerful things that you wouldn't be able to do otherwise.

– Aaron Bertrand
2 hours ago














Agreed, but I'm not saying dynamic SQL is bad. It's really powerful and I do like it actually. I use it in my favor to improve performance in difference situations, and to do whatever I need to customize some routines. When I first suggested, it seemed that it would be a "static stored procedure" or something like that. Using System Stored procedures he would be able to run something like: EXEC DB1.dbo.SP_whatever , EXEC DB2.dbo.SP_whatever. It would be pretty easy to know from which database it comes from.

– Dan
1 hour ago





Agreed, but I'm not saying dynamic SQL is bad. It's really powerful and I do like it actually. I use it in my favor to improve performance in difference situations, and to do whatever I need to customize some routines. When I first suggested, it seemed that it would be a "static stored procedure" or something like that. Using System Stored procedures he would be able to run something like: EXEC DB1.dbo.SP_whatever , EXEC DB2.dbo.SP_whatever. It would be pretty easy to know from which database it comes from.

– Dan
1 hour ago

















draft saved

draft discarded
















































Thanks for contributing an answer to Database Administrators Stack Exchange!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f232169%2fhow-to-get-the-name-of-the-database-a-stored-procedure-is-executed-in-within-tha%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Masuk log Menu navigasi

Identifying “long and narrow” polygons in with PostGISlength and width of polygonWhy postgis st_overlaps reports Qgis' “avoid intersections” generated polygon as overlapping with others?Adjusting polygons to boundary and filling holesDrawing polygons with fixed area?How to remove spikes in Polygons with PostGISDeleting sliver polygons after difference operation in QGIS?Snapping boundaries in PostGISSplit polygon into parts adding attributes based on underlying polygon in QGISSplitting overlap between polygons and assign to nearest polygon using PostGIS?Expanding polygons and clipping at midpoint?Removing Intersection of Buffers in Same Layers

Старые Смолеговицы Содержание История | География | Демография | Достопримечательности | Примечания | НавигацияHGЯOLHGЯOL41 206 832 01641 606 406 141Административно-территориальное деление Ленинградской области«Переписная оброчная книга Водской пятины 1500 года», С. 793«Карта Ингерманландии: Ивангорода, Яма, Копорья, Нотеборга», по материалам 1676 г.«Генеральная карта провинции Ингерманландии» Э. Белинга и А. Андерсина, 1704 г., составлена по материалам 1678 г.«Географический чертёж над Ижорскою землей со своими городами» Адриана Шонбека 1705 г.Новая и достоверная всей Ингерманландии ланткарта. Грав. А. Ростовцев. СПб., 1727 г.Топографическая карта Санкт-Петербургской губернии. 5-и верстка. Шуберт. 1834 г.Описание Санкт-Петербургской губернии по уездам и станамСпецкарта западной части России Ф. Ф. Шуберта. 1844 г.Алфавитный список селений по уездам и станам С.-Петербургской губернииСписки населённых мест Российской Империи, составленные и издаваемые центральным статистическим комитетом министерства внутренних дел. XXXVII. Санкт-Петербургская губерния. По состоянию на 1862 год. СПб. 1864. С. 203Материалы по статистике народного хозяйства в С.-Петербургской губернии. Вып. IX. Частновладельческое хозяйство в Ямбургском уезде. СПб, 1888, С. 146, С. 2, 7, 54Положение о гербе муниципального образования Курское сельское поселениеСправочник истории административно-территориального деления Ленинградской области.Топографическая карта Ленинградской области, квадрат О-35-23-В (Хотыницы), 1930 г.АрхивированоАдминистративно-территориальное деление Ленинградской области. — Л., 1933, С. 27, 198АрхивированоАдминистративно-экономический справочник по Ленинградской области. — Л., 1936, с. 219АрхивированоАдминистративно-территориальное деление Ленинградской области. — Л., 1966, с. 175АрхивированоАдминистративно-территориальное деление Ленинградской области. — Лениздат, 1973, С. 180АрхивированоАдминистративно-территориальное деление Ленинградской области. — Лениздат, 1990, ISBN 5-289-00612-5, С. 38АрхивированоАдминистративно-территориальное деление Ленинградской области. — СПб., 2007, с. 60АрхивированоКоряков Юрий База данных «Этно-языковой состав населённых пунктов России». Ленинградская область.Административно-территориальное деление Ленинградской области. — СПб, 1997, ISBN 5-86153-055-6, С. 41АрхивированоКультовый комплекс Старые Смолеговицы // Электронная энциклопедия ЭрмитажаПроблемы выявления, изучения и сохранения культовых комплексов с каменными крестами: по материалам работ 2016-2017 гг. в Ленинградской области