Can let me know how to remove views/tables from Azure Synapse Inbuilt SQL Serverless Pool.
Its easy enough to remove individual tables/views using following:
use [DatabaseName]
GO
drop EXTERNAL table schemaname.tablename
But I would to remove all the views/tables shown here:
Run the following T-SQL query which builds a dynamic SQL statement to drop all views:
declare #sql nvarchar(max) = (
select STRING_AGG('drop view ['+s.name+'].['+v.name+']; ','
')
from sys.views v
join sys.schemas s on s.schema_id = v.schema_id
where v.is_ms_shipped = 0
)
exec(#sql)
Related
I need to run a query against all databases (that have the same schema), the problem is these are Azure databases within an Elastic Pool. I read that this can be done using the "Central Management Servers" feature in SQL Management Studio but I have installed the latest version 18.3 but when I try and expand the Azure SQL server under "Central Management Servers" I get the following error:
Azure SQL Database cannot be used as a Central Management Server
The type of query I am trying to run against all the databases is as follows, this works fine on a local SQL Server instance but does not work on Azure SQL Server.
SET NOCOUNT ON;
IF OBJECT_ID (N'tempdb.dbo.#temp') IS NOT NULL
DROP TABLE #temp
CREATE TABLE #temp
(
[COUNT] INT
, DB VARCHAR(50)
)
DECLARE #TableName NVARCHAR(50)
SELECT #TableName = '[dbo].[CustomAttributes]'
DECLARE #SQL NVARCHAR(MAX)
SELECT #SQL = STUFF((
SELECT CHAR(13) + 'SELECT ''' + name + ''', COUNT(1) FROM [' + name + '].' + #TableName + 'WHERE dataType = 2'
FROM sys.databases
WHERE OBJECT_ID('[' + name + ']' + '.' + #TableName) IS NOT NULL
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
INSERT INTO #temp (DB, [COUNT])
EXEC sys.sp_executesql #SQL
SELECT *
FROM #temp t
Azure SQL database doesn't support Administer Multiple Servers Using Central Management Servers.
Since your databases are in the same Elastic pool, you can using the Elastic Query to run a query against all databases.
The elastic query feature (in preview) enables you to run a Transact-SQL query that spans multiple databases in Azure SQL Database. It allows you to perform cross-database queries to access remote tables, and to connect Microsoft and third-party tools (Excel, Power BI, Tableau, etc.) to query across data tiers with multiple databases. Using this feature, you can scale out queries to large data tiers in SQL Database and visualize the results in business intelligence (BI) reports.
For more details, please see T-SQL querying:
Reporting across scaled-out cloud databases (preview)
Query across cloud databases with different schemas (preview)
Hope this helps.
I'm having quite the problem.
The process data from our machines is stored in multiple MS SQL Databases.
It is possible to mount and unmount data which is no longer used or which should be archived.
Thats the reason, why there are multiple databases.
In each Database there exists multiple tables with the data values for one or more measuring points.
Which a JOIN Query i can get the values from one table with the corresponding table and tagname:
> SELECT HA_DATA_yyyy.R_xxxxx.time HA_DATA_yyyy.R_xxxxx.value, HA_DATA_yyyy.tags.tagname FROM HA_DATA_yyyy.R_xxxxx
> INNER JOIN HA_DATA_yyyy.RI_xxxxx ON HA_DATA_yyyy.R_xxxxx.id = HA_DATA_yyyy.RI_xxxxx.id
> INNER JOIN HA_DATA_yyyy.tags on HA_DATA_yyyy.RI_xxxxx.tag_uuid = HA_DATA_yyyy.tags.tag_uuid
> WHERE (HA_DATA_yyyy.tags.tagname like 'tagname')
yyyy - represents a number for the database
xxxxx - represents a number which is unique on the database-server, but differents in each database.
But now I'm looking for a solution to get this for all R_xxxxx tables of a database and for all mounted databases.
Is there any way to do this without external software? Just with the right query request or user defined function / stored procedure?
maybe dynamic sql is an option.
as a starting point you could use the list of databases:
insert into #dblist (dbname)
select d.name from sys.databases d where d.name like 'HA_DATA_%'
then for each database gather the list of tables to read data from (you can go with cursors or other loop as you prefer):
declare #dbname varchar(128) = ''
declare #dynsql nvarchar(max)
create table #listoftables (name varchar(128), db varchar(128))
while exists(select top 1 dbname from #dblist where dbname > #dbname order by dbname)
begin
set #dynsql = 'insert into #listoftables(name,db) select name,''' + #db + ''' from '+ #db +'.sys.tables'
exec sp_executesql #statement = #dynsql
-- move on to next db
select top 1 #dbname = dbname from #dblist where dbname > #dbname order by dbname
end
now you have a table list to loop onto to build a dynamic query to read all the data at once.
beware of the many issues you may incur using dynamic sql; here and there you can find just the first 2 results gathered with some explanations on why you have to be careful using dynamic sql.
Please have a look at the answer of this Stackoverflow question:
Archiving large amounts of old data in SQL Server
I think it might be what you need.
Update:
You can query the mounted databases by using the SQL query:
select Name into #myDatabases -- get all mounted databases into #myDatabases
from sys.databases
where (has_dbaccess(name) > 0)
and name not in ('master', 'tempdb', 'model', 'msdb')
order by 1
select * from #myDatabases -- list all mounted databases
drop table #myDatabases -- don't forget to drop it at the end
This can be used to create a dynamic SQL statement, which you execute via the sp_executesql command:
EXECUTE sp_executesql #SQL_String, #Parameter_Definition, #Param1, ..., #ParamN
The parameter definition is a string containing the list of parameter names and their datatypes.
So you can build up your own query based on the database list above and then execute it.
After some searching around i couldn't find a good answer that covers my issue.
I am working on the consolidation of around 100 databases. The structure is the same and they are all on the same server. All the databases have a table with login information.
We have created a core database with all the connection information from the other databases.
Now we need to create a view in the core database that contains all the login credentials from all the databases.
This means we need to use a loop to go through all the databases and select the user name and password.
Any ideas or suggestions are welcome
One possible solution is to create a stored procedure
DECLARE #sql varchar(max), #Database1 varchar(300)
set #Database1 = 'tempdb'
SET #sql='
USE '+#Database1+';
IF EXISTS (SELECT 1 FROM SYS.VIEWS WHERE NAME =''test_view'')
BEGIN
DROP VIEW test_view
PRINT ''VIEW EXISTS''
END'
PRINT #sql
EXEC(#sql)
declare #sql1 varchar(max)
// Modify below query as per your requirement its just for an idea
select #sql1 = IsNull(#sql1 + 'union all ','') +
'select * from ' + name + '.dbo.tblUser'
from sys.databases
where name like 'DbNamePrefix%'
set #sql1 = 'create view dbo.YourView as ' + #sql1
exec (#sql1)
Make a database job and schedule it as per your requirement.
To reference to your tables in the second database use this:
[DBName].[dbo].[TableName]
e.g.
CREATE VIEW [dbo].[ViewName]
as
select
a.ID,
a.Name,
b.Address
from TableA a
join SecondDBName.dbo.Table b
on ... ---Remaining code here...
NOTE: This will work only on the same server - if your databases are on different servers then you will need to create a linked server.
Take a look at this. Can this be one of the answers to your question?
http://blog.springsource.org/2007/01/23/dynamic-datasource-routing/
I would like to run a script to drop the multiple databases from SQL Azure as soon I finish using it. When I tried as following,
DECLARE #dbname varchar(100);
DECLARE #stmt nvarchar(3000);
SET #dbname = '6A732E0B';
SELECT #stmt = (SELECT 'DROP DATABASE [' + name + ']; ' FROM sys.databases
WHERE name LIKE '%' +#dbname +'%');
EXEC sp_executesql #stmt;
SQL Azure throws error message as “The DROP DATABASE statement must be the only statement in the batch”
Can somebody help me on this?
This is a known limitation in SQL Azure - certain statements need to be in a batch by themselves to be executed. This includes CREATE/ALTER DATABASE, ALTER DATABASE and a few more.
To solve you problem, you can create a loop in you application where you iterate over all the databases and drop them by issuing DROP DATABASE statements in separate batches.
I believe this is a bug of SQL Azure. I've recently reported it to Microsoft:
https://connect.microsoft.com/SQLServer/feedback/details/684160/sp-executesql-the-drop-database-statement-must-be-the-only-statement-in-the-batch
How do you force a rename???
Rename failed for Table 'dbo.x. (Microsoft.SqlServer.Smo)
For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=10.0.2531.0+((Katmai_PCU_Main).090329-1045+)&EvtSrc=Microsoft.SqlServer.Management.Smo.ExceptionTemplates.FailedOperationExceptionText&EvtID=Rename+Table&LinkId=20476
An exception occurred while executing a Transact-SQL statement or batch. (Microsoft.SqlServer.ConnectionInfo)
Object '[dbo].[x]' cannot be renamed because the object participates in enforced dependencies. (Microsoft SQL Server, Error: 15336)
For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=09.00.4035&EvtSrc=MSSQLServer&EvtID=15336&LinkId=20476
Find the "enforced dependencies", then remove or disable them.
By "enforced dependencies", it means Schema binding, so you'll have to look specifically for that.
Here's a query to look for schema binding references to your object:
select o.name as ObjName, r.name as ReferencedObj
from sys.sql_dependencies d
join sys.objects o on o.object_id=d.object_id
join sys.objects r on r.object_id=d.referenced_major_id
where d.class=1
AND r.name = #YourObjectName
As I noted in the comments, there is no way to FORCE-ibly override Schema Binding. When you use Schema Binding, you are explicitly saying "Do not let me or anyone else override this." The only way around Schema Binding is to undo it, and that's intentional.
I had the same issue , my problem was that i has a COMPUTED FIELD using the column i was trying to rename.
by running the query from the selected answer i was able to tell that had enforced dependencies, but i was not able to see exactly what was the problem
Try this:
/*
Example 1: Rename a table dbo.MyTable -> dbo.YourTable
EXEC dbo.USP_DROP_ENFORCED_DEPENDENCIES #SchemaName=N'dbo', #EntityName=N'MyTable', #Debug=1;
EXEC sp_rename N'dbo.MyTable', N'YourTable', N'OBJECT'
Example 2: Rename a column dbo.MyTable.MyColumn -> dbo.MyTable.YourColumn
EXEC dbo.USP_DROP_ENFORCED_DEPENDENCIES #SchemaName=N'dbo', #EntityName=N'MyTable', #ColumnName=N'MyColumn' #Debug=1;
EXEC sp_rename N'dbo.MyTable.MyColumn', N'YourColumn', N'COLUMN'
*/
CREATE Procedure dbo.USP_DROP_ENFORCED_DEPENDENCIES
(
#SchemaName sysname = 'dbo',
#EntityName sysname,
#ColumnName sysname = NULL,
#Debug bit = 0
)
AS
BEGIN
SET NOCOUNT ON;
SET ROWCOUNT 0;
DECLARE #ReferencingEntitySchema sysname, #ReferencingEntityName sysname, #ReferencingEntityType nvarchar(8), #SqlScript nvarchar(512);
DECLARE ReferencingEntitiesCursor CURSOR LOCAL FORWARD_ONLY
FOR
SELECT OBJECT_SCHEMA_NAME(dep.referencing_id) AS [schema]
,referencing_entity.name
,CASE referencing_entity.type
WHEN 'V' THEN N'VIEW'
ELSE /*IF, FN, TF*/ N'FUNCTION'
END as [type]
FROM sys.sql_expression_dependencies AS dep
INNER JOIN sys.objects AS referencing_entity
ON dep.referencing_id = referencing_entity.object_id
WHERE dep.referenced_entity_name = #EntityName
AND dep.referenced_schema_name = #SchemaName
AND is_schema_bound_reference = 1
AND ((#ColumnName IS NULL AND dep.referenced_minor_id = 0) OR COL_NAME(dep.referenced_id, dep.referenced_minor_id) = #ColumnName)
OPEN ReferencingEntitiesCursor
FETCH NEXT FROM ReferencingEntitiesCursor
INTO #ReferencingEntitySchema, #ReferencingEntityName, #ReferencingEntityType;
WHILE ##FETCH_STATUS = 0
BEGIN
EXEC dbo.USP_DROP_ENFORCED_DEPENDENCIES #SchemaName=#ReferencingEntitySchema, #EntityName=#ReferencingEntityName, #Debug=#Debug;
--The goal is to produce the following script:
/*
DROP FUNCTION dbo.UFN_SOME_FUNCTION;
OR
DROP VIEW dbo.UFN_SOME_VIEW;
*/
SET #SqlScript = N'DROP ' + #ReferencingEntityType + N' ' + #ReferencingEntitySchema + '.' + #ReferencingEntityName;
IF(#Debug = 1)
RAISERROR (#SqlScript, 0/*severity*/, 0/*state*/) WITH NOWAIT;
EXEC (#SqlScript);
FETCH NEXT FROM ReferencingEntitiesCursor
INTO #ReferencingEntitySchema, #ReferencingEntityName, #ReferencingEntityType;
END
CLOSE ReferencingEntitiesCursor;
DEALLOCATE ReferencingEntitiesCursor;
END
GO
In the SQL Server Object Browser, right-click on the table with the issue and select View Dependencies. Next in the view listed, Right-click (view) and select SCRIPT to CREATE VIEW in New SQL Query Editor window, then remove WITH SCHEMABINDING from the CREATE VIEW t-sql script and run the revised CREATE VIEW t-sql. This unlinks the schema dependency from the table. I was able to recreate the table at this point (DROP, RENAME, etc).
Note:
Schema binding can occur on functions and other objects in your db.
Use of View Dependencies on the object throwing the error is essential
to fix the issue.
BTW:
I originally added schema binding to enable view indexing. Keeping a
good index on the underlying table(s) may mitigate the performance hit
of not having one on the view.
View Dependencies
More on Schema Binding
I had an issue like this. I dropped constraints on this DB object, renamed the DB object then recreated these constraints. This solved my problem.
I used this script to get dependent view with schemabingings:
select distinct o.name, o.type from sys.sql_expression_dependencies dep inner join sys.objects o on dep.referencing_id=o.object_id where referenced_id = OBJECT_ID(<your dependency owner object>) and o.type = 'V'