hy, i have 2 database. DB1 & DB2.
i create SP in DB1. in the SP, i want to access table "TBL" in DB2.
how can i create that SP??
CREATE PROCEDURE test
AS
BEGIN
??????????
END; Thx,
hy, i have 2 database. DB1 & DB2.
i create SP in DB1. in the SP, i want to access table "TBL" in DB2.
how can i create that SP??
CREATE PROCEDURE test
AS
BEGIN
??????????
END; Thx,
As already demonstrated and confirmed, a stored procedure in one database can read objects in another. A few practical tips will help avoid permission headaches and make the code easier to maintain.
Create a local synonym in DB1 that points to the DB2 table. That lets your proc use a short name and makes it simpler to change the target later:
CREATE SYNONYM dbo.TBL FOR DB2.dbo.TBL; If callers of the procedure should not have direct rights on DB2, run the proc under a different execution context instead of granting broad rights to every user. One approach is to create the proc with an explicit execution context:
CREATE PROCEDURE dbo.test
WITH EXECUTE AS OWNER
AS
BEGIN
-- reference the external object here
END; Important cautions and troubleshooting checklist:
EXECUTE AS / module signing if you want to avoid granting users cross-database permissions.USE inside a proc; prefer schema-qualified names or synonyms.Further reading: see Microsoft documentation on creating synonyms (CREATE SYNONYM), execution context (EXECUTE AS), cross-database ownership chaining (), and linked servers (sp_addlinkedserver).
Jump to Post— samaru 145The syntax
SELECT * FROM [DATABASENAME].[SCHEMA].[TABLE]So let's say you're in the Northwind database and you wanted to query a table in the Pubs database, you would do the following:
SELECT * FROM Pubs.dbo.Authors
The syntax
SELECT * FROM [DATABASENAME].[SCHEMA].[TABLE] So let's say you're in the Northwind database and you wanted to query a table in the Pubs database, you would do the following:
SELECT * FROM Pubs.dbo.Authors thx,
its work!!
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.