Dropping all tables in Sybase ASE including those with constraints - sap-ase

What is the best way to completely drop all tables in a database in Sybase ASE without dropping the database? I have been using a script: from this question but I am getting errors trying to drop all tables in a database due to referential integrity.
In MySQL I could use SET FOREIGN_KEY_CHECKS = 0
Is there a way to do this in Sybase ASE or can the script above be extended to loop through the constraints?

First you have to drop constraints:
declare cur cursor
for
select SOR.Name as constraint, SOT.Name as table
from sysreferences SR
join sysobjects SOR on SOR.id = SR.constrid
join sysconstraints SC on SC.constrid = SR.constrid
join sysobjects SOT on SOT.id = SC.tableid
go
declare #constraint varchar(500)
declare #table varchar(500)
declare #SQL varchar(500)
open cur
fetch cur into #constraint,#table
while (##sqlstatus = 0)
begin
select #SQL = 'alter table '+#table+' drop '+#constraint
exec( #SQL)
fetch cur into #constraint,#table
end
close cur
deallocate cursor cur
next you can drop tables.

The procedure to drop all constraints in the accepted answer did not work for me. Here is a modified version which works in my ASE16.
BEGIN
declare cur cursor
for
select o.name, t.name from sysreferences r
join sysobjects o on o.id = r.constrid
join sysconstraints c on c.constrid = r.constrid
join sysobjects t on t.id = c.tableid
END
GO
--
declare #constraint varchar(500)
declare #table varchar(500)
declare #SQL varchar(500)
--
open cur
fetch cur into #constraint,#table
while (##sqlstatus = 0)
begin
--
select #SQL = 'alter table '+#table+' drop constraint '+#constraint
exec( #SQL)
fetch cur into #constraint,#table
--
end
close cur
deallocate cursor cur

the above logic is correct but the query is wrong and you might get issues with the "constraint" and "table" keywords.
use something like constriantName and tableName in line 3
The query is missing "constraint", correct query:
'alter table ' + #table + ' drop constraint ' +#constraint

Related

Is there a way to disable and re enable FOREIGN KEY constraints for a database Azure SQL

I'm trying to truncate some tables in a database. Some of these tables have foreign keys. So when I try to truncate them I get the following error.
Cannot truncate table 'IDN_OAUTH2_ACCESS_TOKEN' because it is being
referenced by a FOREIGN KEY constraint.
Is there a way to disable FOREIGN KEY constraints in Azure SQL (Microsoft SQL Azure (RTM) - 12.0.2000.8) and re-enable them? In MySQL, I have done the same using the following script.
SET FOREIGN_KEY_CHECKS=0;
TRUNCATE TABLE IDN_OAUTH2_ACCESS_TOKEN;
SET FOREIGN_KEY_CHECKS=1;
I think we can write some T-SQL scripts to achieve that. Using T-SQL to splice T-SQL(add & drop FK index) commands.
We can use following script to query all the FK and then copy the query result into a text. We can use the query result to rebuild foreign key index.
select
concat(concat('alter table ',c.CONSTRAINT_SCHEMA),concat('.',fk.TABLE_NAME)),
concat(' add constraint ', c.CONSTRAINT_NAME), --cu.COLUMN_NAME
concat(' foreign key( ',cu.COLUMN_NAME),
concat(concat(') references ',c.CONSTRAINT_SCHEMA),concat('.',pk.TABLE_NAME)),
concat(concat('(',pt.COLUMN_NAME),');')
from
INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS c
inner join INFORMATION_SCHEMA.TABLE_CONSTRAINTS fk
on c.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
inner join INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk
on c.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
inner join INFORMATION_SCHEMA.KEY_COLUMN_USAGE cu
on c.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
inner join (
select
i1.TABLE_NAME,
i2.COLUMN_NAME
from
INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
inner join INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2
on i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
where
i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
) PT
on pt.TABLE_NAME = pk.TABLE_NAME
We can replace the add constraint to drop constraint. As follows:
select
concat(concat('alter table ',c.CONSTRAINT_SCHEMA),concat('.',fk.TABLE_NAME)),
concat(' drop constraint ', c.CONSTRAINT_NAME), --cu.COLUMN_NAME
concat(' foreign key( ',cu.COLUMN_NAME)
from
INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS c
inner join INFORMATION_SCHEMA.TABLE_CONSTRAINTS fk
on c.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
inner join INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk
on c.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
inner join INFORMATION_SCHEMA.KEY_COLUMN_USAGE cu
on c.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
inner join (
select
i1.TABLE_NAME,
i2.COLUMN_NAME
from
INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
inner join INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2
on i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
where
i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
) PT
on pt.TABLE_NAME = pk.TABLE_NAME
So you can drop FKs and after truncate some tables, then rebuid FKs.

How can I add primary key and foreign key constraints after export data from Azure SQL

I'm using SQL Server Management Studio 19 to migrate data from source database to target database.
I select SQL Server Native Client 11.0 as the Data Source.
For Destination I also use "SQL Server Native Client 11.0" and choose target database as destination.
The data was exported successfully but primary key and foreign key constraints aren't there. What do I missed?
Any help or any suggestions are appreciated. Thank you so much!
There are two ways to export the PK and FK.
Using SSMS to generate the sql script. We just need to select the tables. It will generate a script.sql in your local PC.
We also can write some scripts to export the PK and FK of the User tables manually.
I've created a sql script to export PK and FK from system tables and views.
2.1 We can use the following script to export PK.
select case when colNo = 1 then concat('alter table ',concat(concat(res.schemaName,'.'),res.tableName)) else '' end headerOne,
case when colNo = 1 then concat(concat('add constraint ' , res.PKName),' primary key( ') else '' end headerTwo,
case when colNo = 1 then colName else concat(',',colName) end headerThree,
case when colNo = s2.maxRow then ');' else '' end as headerFour
from (
select s.name as schemaName,i.name as PKName,ov.name as tableName,c.name as colName,k.colid as colNo,k.keyno as indexNO
from
sysindexes i
join sysindexkeys k on i.id = k.id and i.indid = k.indid
join sysobjects o on i.id = o.id
join sys.objects ov on o.id = ov.object_id
join sys.schemas s ON ov.schema_id = s.schema_id
join syscolumns c on i.id=c.id and k.colid = c.colid
where o.xtype = 'U' and exists(select 1 from sysobjects where xtype = 'PK' and name = i.name)
) res
left join
(select schemaName,PKName,tableName,max(rono) as maxRow
from
(
select s.name as schemaName,i.name as PKName,ov.name as tableName,c.name as colName, ROW_NUMBER() OVER (PARTITION BY s.name,i.name,ov.name ORDER BY o.name,k.colid) AS rono
from
sysindexes i
join sysindexkeys k on i.id = k.id and i.indid = k.indid
join sysobjects o on i.id = o.id
join sys.objects ov on o.id = ov.object_id
join sys.schemas s ON ov.schema_id = s.schema_id
join syscolumns c on i.id=c.id and k.colid = c.colid
where o.xtype = 'U' and exists(select 1 from sysobjects where xtype = 'PK' and name = i.name)
) s1
group by schemaName,PKName,tableName
) s2 on res.schemaName = s2.schemaName and res.PKName=s2.PKName and res.tableName=s2.tableName
2.2 Then we can copy the script from SSMS.
2.3 Then we paste the script to query window of the Staging database to execute the script.
2.4 After created PK, in the same way, we can export FK and create them.
select
concat(concat('alter table ',c.CONSTRAINT_SCHEMA),concat('.',fk.TABLE_NAME)),
concat(' add constraint ', c.CONSTRAINT_NAME), --cu.COLUMN_NAME
concat(' foreign key( ',cu.COLUMN_NAME),
concat(concat(') references ',c.CONSTRAINT_SCHEMA),concat('.',pk.TABLE_NAME)),
concat(concat('(',pt.COLUMN_NAME),');')
from
INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS c
inner join INFORMATION_SCHEMA.TABLE_CONSTRAINTS fk
on c.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
inner join INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk
on c.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
inner join INFORMATION_SCHEMA.KEY_COLUMN_USAGE cu
on c.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
inner join (
select
i1.TABLE_NAME,
i2.COLUMN_NAME
from
INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
inner join INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2
on i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
where
i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
) PT
on pt.TABLE_NAME = pk.TABLE_NAME

Query and get all database names and subquery especific tables from all databases

I have different databases. I have tables within each database.
I would like to know if I can ask how many databases excluding some such as 'schema' 'mysql' I have once know how to perform a subquery asked by a particular table of all the databases resulting from the first question.
example.
the structure would be
db1 -> user-> id,name,imei,telephone,etc..
db2 -> user-> id,nameuser,imei,telephone,etc..
db3 -> user-> id,nameuser,imei,telephone,etc..
....
db1000 -> user-> id,nameuser,imei,telephone,etc..
the query are how this, but this get error
SELECT CONCAT('SELECT * FROM ' schema_name 'where imei.'schema_name = nameimai)
FROM information_schema.schemata
WHERE schema_name NOT IN ('information_schema','mysql','performance_schema','sys','performance_schema','phpmyadmin');
Results
name db id name imei phone
---------- ---------- ---------- ---------- ----------
db1 1 John 76876876 xxx
db2 2300 John 76876876 xxxx
...
db1000 45 John 76876876 xxx
its possible in one query
thanks..
Here's one way you could do it with a stored procedure.
If I understand correctly, you have multiple databases with identical tables (user) and you want to run a query against all these tables for a specific value.
I've made this fairly general so that you can pass in the table name and also the where clause. Your example seemed to be looking for user records with imei = '76876876', so if we use that example.
USE test;
DELIMITER //
DROP PROCEDURE IF EXISTS multidb_select //
-- escape any quotes in the query string
-- call multidb_select ('usertest','WHERE imei = \'76876876\'')
CREATE PROCEDURE multidb_select(IN tname VARCHAR(64), IN qwhere VARCHAR(1024))
READS SQL DATA
BEGIN
DECLARE vtable_schema VARCHAR(64);
DECLARE vtable_name VARCHAR(64);
DECLARE done BOOLEAN DEFAULT FALSE;
-- exclude views and system tables
DECLARE cur1 CURSOR FOR
SELECT `table_schema`, `table_name`
FROM `information_schema`.`tables`
WHERE `table_name` = tname
AND `table_type` = 'BASE TABLE'
AND `table_schema` NOT IN
('information_schema','mysql','performance_schema',
'sys','performance_schema','phpmyadmin')
ORDER BY `table_schema` ASC;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done := TRUE;
OPEN cur1;
SET #unionall := '';
read_loop: LOOP
FETCH cur1 INTO vtable_schema, vtable_name;
IF done THEN
LEAVE read_loop;
END IF;
-- UNION ALL in case the id is the same
IF CHAR_LENGTH(#unionall) = 0 THEN
SET #unionall =
CONCAT("SELECT \'", vtable_schema , "\' AS 'Db', t.* FROM `",
vtable_schema, "`.`" , vtable_name, "` t ", qwhere);
ELSE
SET #unionall =
CONCAT(#unionall, " UNION ALL SELECT \'", vtable_schema ,
"\' AS 'Db', t.* FROM `", vtable_schema,
"`.`", vtable_name, "` t ", qwhere);
END IF;
END LOOP;
CLOSE cur1;
PREPARE stmt FROM #unionall;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END //
DELIMITER ;
Run it with
call test.multidb_select('user','WHERE imei = \'76876876\'')

Insert the data into the remote table from # temp table in the stored procedure

I have a stored procedure in AZURE SQL database.In that there is a requirement to insert the records into the remote table from #temp table.
As xxxx_table is in the remote database used sp_execute_remote.
below is the scenario:
Create Procedure SP1 parameter1, Parameter2
As
select Distinct B.column1, B.Column2
into #A
from (Query1
Union
Query2) B
if (select count(1) from #A) > 0
Begin
Exec sp_execute_remote #data_source_name = N'Remotedatabase',
#stmt = N'INSERT INTO [dbo].[xxxx_table]
SELECT DISTINCT
'xxx' AS 'column1',
'xxx as 'Column2',
'xxx' AS 'Column3',
'xxx' AS 'Column4',
'xxx' AS Column4
FROM #A A INNER JOIN table1 on A.Column1 = Table1.Column2'
End
)
Getting the syntax error as below:
Incorrect syntax near 'xxx'.
Where am i going wrong? or let me know if there is another way to achieve this.
If you need to dynamically build a string in SQL single-quote the whole sentence, or use 'some text' + 'another text' to concat sentences. If you must add single quote use a double single quote ''
Example:
DECLARE #param1 int;
DECLARE #param1 VARCHAR(10);
SET #param1 = 10;
SET #param2 = 'CCDOS87'
#Stmt = 'SELECT Field1 FROM TableName WHERE Field1 = '
+ CAST(#param1 AS VARCHAR(100))
+ ' AND Field1 = '''
+ param2
+ ''''; <- This is a single '
#stmt = N'INSERT INTO [dbo].[Error_table]
SELECT DISTINCT
xxx AS column1,
xxx as Column2,
xxx AS Column3,
xxx AS Column4,
xxx AS Environment
FROM #A A INNER JOIN table1 on A.Column1 = Table1.Column2'
update
If your tables are in different databases but in the same server use:
INSERT INTO SERVER.SCHEMA.TABLE_NAME
SELECT Something
FROM SERVER.SCHEMA.TABLE_NAME

How to optimize DELETE .. NOT IN .. SUBQUERY in Firebird

I've this kind of delete query:
DELETE
FROM SLAVE_TABLE
WHERE ITEM_ID NOT IN (SELECT ITEM_ID FROM MASTER_TABLE)
Are there any way to optimize this?
You can use EXECUTE BLOCK for sequential scanning of detail table and deleting records where no master record is matched.
EXECUTE BLOCK
AS
DECLARE VARIABLE C CURSOR FOR
(SELECT d.id
FROM detail d LEFT JOIN master m
ON d.master_id = m.id
WHERE m.id IS NULL);
DECLARE VARIABLE I INTEGER;
BEGIN
OPEN C;
WHILE (1 = 1) DO
BEGIN
FETCH C INTO :I;
IF(ROW_COUNT = 0)THEN
LEAVE;
DELETE FROM detail WHERE id = :I;
END
CLOSE C;
END
(NOT) IN can usually be optimized by using (NOT) EXISTS instead.
DELETE
FROM SLAVE_TABLE
WHERE NOT EXISTS (SELECT 1 FROM MASTER_TABLE M WHERE M.ITEM_ID = ITEM_ID)
I am not sure what you are trying to do here, but to me this query indicates that you should be using foreign keys to enforce these kind of constraints, not run queries to cleanup the mess afterwards.

Resources