I've got the following code I've put together which seems to work just fine. However, I need to put it within a stored procedure, but I get the following error:
a use statement is not allowed in a procedure, function or trigger
Anyone know of a work around?
CREATE TABLE #TableRowCounts1
(
[TableName] VARCHAR(128),
[RowCount] INT
)
CREATE TABLE #TableRowCounts2
(
[TableName] VARCHAR(128),
[RowCount] INT
)
use Database1
GO
INSERT INTO #TableRowCounts1
(
[TableName],
[RowCount]
)
EXEC sp_MSforeachtable
'SELECT ''?''
[TableName],
COUNT(*) [RowCount]
FROM ?'
use Database2
GO
INSERT INTO #TableRowCounts2
(
[TableName],
[RowCount]
)
EXEC sp_MSforeachtable
'SELECT ''?''
[TableName],
COUNT(*) [RowCount]
FROM ?'
If you're talking about a USE statement inside the sproc, then no, you can't do that. The sproc is already scoped by the DB it was created in. If you want to access another DB you need to use three-part naming, e.g. ELECS.
Trigger: Trigger can't be called from Store Procedure or Function. Store procedure: Stored Procedures can accept any type of parameter. Stored Procedures also accept out parameter. Function: Function can accept any type of parameter.
The SQL USE statement is used to select any existing database in the SQL schema.
You cannot call a procedure in a select statement, because it does not return anything.
You should change it to work like that. You need to specify the fully qualified name by using the database (and schema) in front of the stored procs you want to run on different databases.
CREATE PROCEDURE SomeProc
AS
CREATE TABLE #TableRowCounts1
(
[TableName] VARCHAR(128),
[RowCount] INT
)
CREATE TABLE #TableRowCounts2
(
[TableName] VARCHAR(128),
[RowCount] INT
)
INSERT INTO #TableRowCounts1
(
[TableName],
[RowCount]
)
EXEC Database1.[dbo].sp_MSforeachtable
'SELECT ''?''
[TableName],
COUNT(*) [RowCount]
FROM ?'
INSERT INTO #TableRowCounts2
(
[TableName],
[RowCount]
)
EXEC Database2.[dbo].sp_MSforeachtable
'SELECT ''?''
[TableName],
COUNT(*) [RowCount]
FROM ?'
Instead of using USE statement you can simply use a fully qualified name i.e
DATABASENAME.SCHEMANAME.TABLENAME.ColumnName
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With