Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

a use statement is not allowed in a procedure, function or trigger

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 ?'

like image 880
Philip Avatar asked Oct 14 '13 00:10

Philip


People also ask

Can I use use statement in stored procedure?

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.

Can we use procedure and function in trigger?

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.

What is the function of the use statement in SQL?

The SQL USE statement is used to select any existing database in the SQL schema.

Can we use select statement in procedure?

You cannot call a procedure in a select statement, because it does not return anything.


2 Answers

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 ?'
like image 82
Szymon Avatar answered Oct 08 '22 21:10

Szymon


Instead of using USE statement you can simply use a fully qualified name i.e

DATABASENAME.SCHEMANAME.TABLENAME.ColumnName
like image 4
M.Ali Avatar answered Oct 08 '22 19:10

M.Ali