Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
238 views
in Technique[技术] by (71.8m points)

sql server - How to delete particular common record from all tables in particular schema (T SQL)?

I have tables in a database with three schemas (schema1, schema2, schema3). Each schema has 2 tables (schema1.table1, schema1.table2, schema2.table1, schema2.table2........) each table has ID column which has values like 17, 18, 19, 20, 50 etc. I want to delete record 19 from all tables in schema1, something like > DELETE ID 19 from ALL tables in Schema1. Is there any way to do that? Appreciate any help Thanks

question from:https://stackoverflow.com/questions/65852841/how-to-delete-particular-common-record-from-all-tables-in-particular-schema-t-s

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Sure it could be done by Dynamic sql, you will get all your needed table into a temp table with an identity column [id].

CREATE TABLE #temp ---identity column will be used to iterate
(
id INT IDENTITY,
SchemaName VARCHAR(20),
TableName VARCHAR(20),
ColumnName VARCHAR(20)
)
INSERT INTO #temp
SELECT TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
-- choose your own results with where conditions

DECLARE @SQL VARCHAR(MAX)
DECLARE @Count INT = 1
DECLARE @Schema VARCHAR(20)
DECLARE @Table VARCHAR(20)
DECLARE @Column VARCHAR(20)

WHILE @COUNT <= (SELECT COUNT(*) FROM #temp) 
BEGIN
    SELECT @Schema = SchemaName FROM  #temp WHERE id = @Count
    select @table = TABLENAME FROM #temp WHERE id = @Count
    SELECT @Column = COLUMNNAME FROM #temp WHERE id = @Count
    
    SELECT @sql = 'DELECT FROM '+@Schema+'.'+@Table+ 'WHERE ID = 19'

    --PRINT @SQL
SET @Count = @Count + 1

END

change PRINT to Exec if your printed query looks good to you.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...