使用带有 WHERE 条件的单个查询 (SQL Express 2005) 从多个表中删除行

发布于 2024-08-11 00:29:15 字数 252 浏览 11 评论 0原文

这是我正在使用的查询:

 DELETE TB1.*, TB2.*
   FROM TB1
        INNER JOIN TB2 ON TB1.PersonID = TB2.PersonID 
  WHERE (TB1.PersonID)='2'

它在 MS Access 中工作正常,但在 SQL Server Express 2005 中出现错误(“,”附近的语法不正确。)。

如何解决?请帮忙。

This is the query I'm using:

 DELETE TB1.*, TB2.*
   FROM TB1
        INNER JOIN TB2 ON TB1.PersonID = TB2.PersonID 
  WHERE (TB1.PersonID)='2'

It's working fine in MS Access but getting error (Incorrect syntax near ','.) in SQL Server Express 2005.

How to solve it? Please help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(16

奶茶白久 2024-08-18 00:29:15

您无法在 SQL 2005 或任何其他标准 SQL 中使用单个表达式从多个表中进行DELETEAccess 是这里的例外。

获得此效果的最佳方法是使用 ON DELETE trigger 在表之间指定 FOREIGN KEYS

You cannot DELETE from multiple tables with a single expression in SQL 2005 - or any other standard SQL for that matter. Access is the exception here.

The best method to get this effect is to specify FOREIGN KEYS between the table with an ON DELETE trigger.

天煞孤星 2024-08-18 00:29:15

为什么不使用 DELETE CASCADE FK

Why you don't use a DELETE CASCADE FK ?

知足的幸福 2024-08-18 00:29:15

这不可能在一份声明中完成。您将必须使用 2 个语句

DELETE FROM TB1 WHERE PersonID = '2';
DELETE FROM TB2 WHERE PersonID = '2';

This cannot be done in one statement. You will have to use 2 statements

DELETE FROM TB1 WHERE PersonID = '2';
DELETE FROM TB2 WHERE PersonID = '2';
↘紸啶 2024-08-18 00:29:15

据我所知,你不能用一句话来做到这一点。

但是您可以构建一个存储过程,在事务中的任何表中执行所需的删除操作,这几乎是相同的。

As i know, you can't do it in a sentence.

But you can build an stored procedure that do the deletes you want in whatever table in a transaction, what is almost the same.

泡沫很甜 2024-08-18 00:29:15

我认为您不能一次从多个表中删除(尽管我不确定)。

然而,在我看来,最好通过级联删除的关系来实现这种效果。如果您这样做,您将能够从一个表中删除记录,而另一个表中的记录将被自动删除。

举个例子,假设这两个表代表一个客户,以及该客户的订单。如果你设置了级联删除的关系,你只需删除客户表中的记录,订单就会自动删除。

请参阅有关级联引用完整性约束的 MSDN 文档。

I don't think you can delete from multiple tables at once (though I'm not certain).

It sounds to me, however, that you would be best to achieve this effect with a relationship that cascades deletes. If you did this you would be able to delete the record from one table and the records in the other would be automatically deleted.

As an example, say the two tables represent a customer, and the customer's orders. If you setup the relationship to cascade deletes, you could simply delete record in the customer table, and the orders would get deleted automatically.

See the MSDN doc on cascading referential integrity constraints.

难忘№最初的完美 2024-08-18 00:29:15

为明细表指定外键,引用主表的主键,并设置删除规则 = Cascade 。

现在,当您从主表中删除一条记录时,基于删除行主键值的所有其他详细表记录将被自动删除。

因此,在这种情况下,主表的单个删除查询可以删除主表数据以及子表数据。

Specify foreign key for the details tables which references to the primary key of master and set Delete rule = Cascade .

Now when u delete a record from the master table all other details table record based on the deleting rows primary key value, will be deleted automatically.

So in that case a single delete query of master table can delete master tables data as well as child tables data.

阳光下的泡沫是彩色的 2024-08-18 00:29:15

在程序中使用它

declare cu cursor for SELECT [name] FROM sys.Tables where [name] like 'tbl_%'
declare @table varchar(100)
declare @sql nvarchar(1000)

OPEN cu  
FETCH NEXT FROM cu INTO @table 

WHILE @@FETCH_STATUS = 0  
BEGIN  
    set @sql = N'delete from ' + @table
    EXEC sp_executesql @sql
    FETCH NEXT FROM cu INTO @table 
END   
CLOSE cu;  
DEALLOCATE cu;

Use this in procedure

declare cu cursor for SELECT [name] FROM sys.Tables where [name] like 'tbl_%'
declare @table varchar(100)
declare @sql nvarchar(1000)

OPEN cu  
FETCH NEXT FROM cu INTO @table 

WHILE @@FETCH_STATUS = 0  
BEGIN  
    set @sql = N'delete from ' + @table
    EXEC sp_executesql @sql
    FETCH NEXT FROM cu INTO @table 
END   
CLOSE cu;  
DEALLOCATE cu;
强者自强 2024-08-18 00:29:15

我不知道为什么人们让这件事变得如此困难。可以从多个表中删除行。这是我有效的查询语句。

$sql = "DELETE clients, equine_notes, client_horses FROM clients INNER JOIN client_horses ON client_horses.cID = clients.id INNER JOIN equine_notes ON equine_notes.cID = clients.id WHERE clients.id = '".$cID."'";

客户表有客户的姓名。 client_horses 是客户拥有多少匹马的多行,equine_notes 是我对特定马匹所做的注释。我可以使用 INNER JOIN 子句通过一个查询语句删除与该客户端相关的所有内容。

希望这有帮助

I'm not sure why folks make this so difficult. It is possible to DELETE rows from multiple tables. Here is my query statement that works.

$sql = "DELETE clients, equine_notes, client_horses FROM clients INNER JOIN client_horses ON client_horses.cID = clients.id INNER JOIN equine_notes ON equine_notes.cID = clients.id WHERE clients.id = '".$cID."'";

The clients table has the client's name. The client_horses are multiple rows of how many horses the client owns and equine_notes are notes that I have made on specific horses. I can delete everything pertaining to this client with the one query statement using the INNER JOIN clause.

Hope this helps

伴我老 2024-08-18 00:29:15

我用它来清理测试/开发数据库中的数据。您可以按表名称和记录数进行过滤。

DECLARE @sqlCommand VARCHAR(3000);
DECLARE @tableList TABLE(Value NVARCHAR(128));
DECLARE @TableName VARCHAR(128);
DECLARE @RecordCount INT;

-- get a cursor with a list of table names and their record counts
DECLARE MyCursor CURSOR FAST_FORWARD
FOR SELECT t.name TableName,
           i.rows Records
    FROM sysobjects t,
         sysindexes i
    WHERE 
          t.xtype = 'U'              -- only User tables
          AND i.id = t.id          
          AND i.indid IN(0, 1)       -- 0=Heap, 1=Clustered Index
          AND i.rows < 10            -- Filter by number of records in the table
          AND t.name LIKE 'Test_%';  -- Filter tables by name. You could also provide a list:
                                     -- AND t.name IN ('MyTable1', 'MyTable2', 'MyTable3');
                                     -- or a list of tables to exclude:
                                     -- AND t.name NOT IN ('MySpecialTable', ... );

OPEN MyCursor;

FETCH NEXT FROM MyCursor INTO @TableName, @RecordCount;

-- for each table name in the cursor, delete all records from that table:
WHILE @@FETCH_STATUS = 0
    BEGIN
        SET @sqlCommand = 'DELETE FROM ' + @TableName;
        EXEC (@sqlCommand);
        FETCH NEXT FROM MyCursor INTO @TableName, @RecordCount;
    END;

CLOSE MyCursor;
DEALLOCATE MyCursor;

参考信息:

I use this for cleaning up data in test/development databases. You can filter by table name and record count.

DECLARE @sqlCommand VARCHAR(3000);
DECLARE @tableList TABLE(Value NVARCHAR(128));
DECLARE @TableName VARCHAR(128);
DECLARE @RecordCount INT;

-- get a cursor with a list of table names and their record counts
DECLARE MyCursor CURSOR FAST_FORWARD
FOR SELECT t.name TableName,
           i.rows Records
    FROM sysobjects t,
         sysindexes i
    WHERE 
          t.xtype = 'U'              -- only User tables
          AND i.id = t.id          
          AND i.indid IN(0, 1)       -- 0=Heap, 1=Clustered Index
          AND i.rows < 10            -- Filter by number of records in the table
          AND t.name LIKE 'Test_%';  -- Filter tables by name. You could also provide a list:
                                     -- AND t.name IN ('MyTable1', 'MyTable2', 'MyTable3');
                                     -- or a list of tables to exclude:
                                     -- AND t.name NOT IN ('MySpecialTable', ... );

OPEN MyCursor;

FETCH NEXT FROM MyCursor INTO @TableName, @RecordCount;

-- for each table name in the cursor, delete all records from that table:
WHILE @@FETCH_STATUS = 0
    BEGIN
        SET @sqlCommand = 'DELETE FROM ' + @TableName;
        EXEC (@sqlCommand);
        FETCH NEXT FROM MyCursor INTO @TableName, @RecordCount;
    END;

CLOSE MyCursor;
DEALLOCATE MyCursor;

Reference info:

吹泡泡o 2024-08-18 00:29:15

通常,我使用一个查询从多个表中进行删除。
它适用于 PostgreSQL,但不适用于 MSSQL,这就是我来这里的原因。

使用Postgres(我不知道其他数据库),你可以这样做:

WITH obsolete_ids AS (
    SELECT pr_r."ID" AS ids
    FROM "PULL_REQUEST" pr_r
    WHERE 1=1
    AND pr_r."STATUS" IN (1)
) , del_commit_junc AS (
DELETE 
FROM "PR_TO_COMMIT"
WHERE "REQUEST_ID" IN (SELECT ids FROM obsolete_ids)
)
DELETE
FROM "PULL_REQUEST" pr_out
WHERE pr_out ."ID" IN (SELECT ids FROM obsolete_ids)

实际上,在我原来的查询中,我从另外两个表中删除了外键,但在这里我只是粘贴了一个示例。
这样我解决了“PR_TO_COMMIT”表中的外键问题。

Generally I do deletions from multiple tables with one query.
It works correct with PostgreSQL, but doesn't work for MSSQL, and that's why I got here.
With Postgres (I don't know about other DBs) you can do:

WITH obsolete_ids AS (
    SELECT pr_r."ID" AS ids
    FROM "PULL_REQUEST" pr_r
    WHERE 1=1
    AND pr_r."STATUS" IN (1)
) , del_commit_junc AS (
DELETE 
FROM "PR_TO_COMMIT"
WHERE "REQUEST_ID" IN (SELECT ids FROM obsolete_ids)
)
DELETE
FROM "PULL_REQUEST" pr_out
WHERE pr_out ."ID" IN (SELECT ids FROM obsolete_ids)

Actually In my original Query I delete foreign keys from 2 more tables, but here I just paste an example.
That way I solved problem with Foreign Keys in "PR_TO_COMMIT" table.

野却迷人 2024-08-18 00:29:15

我使用的方式从 SQL Server 中的多个表中删除行?
最重要的是在表中创建外键时使用ondeletecascade

#Table 1 Create:# 
    
create table Customer_tbl 
(
C_id int primary key, 
C_Name varchar(50), 
C_Address varchar(max), 
City varchar(50)
);


#Table 2: Create with Foreign Key Constraints#

create table [order] 
(
Ord_Id int primary key, 
Item varchar(50), 
Quantity int, 
Price_Of_1 int, 
C_id int foreign key references Customer_tbl(C_id)
on delete cascade

);

delete from Customer_tbl where C_id = 2;

The way I am using to Delete rows from multiple tables in SQL Server?
The most important is to use on delete cascade when creating a foreign key in the table

#Table 1 Create:# 
    
create table Customer_tbl 
(
C_id int primary key, 
C_Name varchar(50), 
C_Address varchar(max), 
City varchar(50)
);


#Table 2: Create with Foreign Key Constraints#

create table [order] 
(
Ord_Id int primary key, 
Item varchar(50), 
Quantity int, 
Price_Of_1 int, 
C_id int foreign key references Customer_tbl(C_id)
on delete cascade

);

delete from Customer_tbl where C_id = 2;
一百个冬季 2024-08-18 00:29:15
CREATE PROCEDURE sp_deleteUserDetails
    @Email varchar(255)
AS
    declare @tempRegId as int
    Delete UserRegistration where Email=@Email  
    set @tempRegId = (select Id from UserRegistration where Email = @Email)
    Delete UserProfile where RegID=@tempRegId

RETURN 0
CREATE PROCEDURE sp_deleteUserDetails
    @Email varchar(255)
AS
    declare @tempRegId as int
    Delete UserRegistration where Email=@Email  
    set @tempRegId = (select Id from UserRegistration where Email = @Email)
    Delete UserProfile where RegID=@tempRegId

RETURN 0
谜泪 2024-08-18 00:29:15

您可以使用类似以下内容:

DECLARE db_cursor CURSOR FOR  
SELECT name 
FROM master.dbo.sysdatabases 
WHERE name IN ("TB2","TB1")  -- use these databases

OPEN db_cursor   
FETCH NEXT FROM db_cursor INTO @name   


WHILE @@FETCH_STATUS = 0   
BEGIN   

       DELETE FROM @name WHERE PersonID ='2'

       FETCH NEXT FROM db_cursor INTO @name   
END  

You can use something like the following:

DECLARE db_cursor CURSOR FOR  
SELECT name 
FROM master.dbo.sysdatabases 
WHERE name IN ("TB2","TB1")  -- use these databases

OPEN db_cursor   
FETCH NEXT FROM db_cursor INTO @name   


WHILE @@FETCH_STATUS = 0   
BEGIN   

       DELETE FROM @name WHERE PersonID ='2'

       FETCH NEXT FROM db_cursor INTO @name   
END  
梦与时光遇 2024-08-18 00:29:15

尝试这个查询

DELETE TB1, TB2 FROM TB1 INNER JOIN TB2  
WHERE TB1.PersonID = TB2.PersonID and TB1.PersonID = '2'

Try this query

DELETE TB1, TB2 FROM TB1 INNER JOIN TB2  
WHERE TB1.PersonID = TB2.PersonID and TB1.PersonID = '2'
属性 2024-08-18 00:29:15

$qry = "从 Lesson_game 中删除 lg., l. lg 在 lg.lesson_id = l.id 上右连接课程 l,其中 l.id = ?";

课程是主表和
Lessons_game 是子表,因此右连接

$qry = "DELETE lg., l. FROM lessons_game lg RIGHT JOIN lessons l ON lg.lesson_id = l.id WHERE l.id = ?";

lessons is Main table and
lessons_game is subtable so Right Join

夜访吸血鬼 2024-08-18 00:29:15
DELETE TB1, TB2
    FROM customer_details
        LEFT JOIN customer_booking on TB1.cust_id = TB2.fk_cust_id
    WHERE TB1.cust_id = $id
DELETE TB1, TB2
    FROM customer_details
        LEFT JOIN customer_booking on TB1.cust_id = TB2.fk_cust_id
    WHERE TB1.cust_id = $id
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文