ประกาศรายการตัวแปรในขั้นตอนการจัดเก็บ SQL Server

ฉันต้องการลบข้อมูลออกจากหลายตารางที่มีเงื่อนไขเดียวกัน (where clause) สำหรับแต่ละคำสั่งลบ

delete from tblA where id in (select x.id from tblX x where name like N'%test%')
delete from tblB where id in (select x.id from tblX x where name like N'%test%')
delete from tblC where id in (select x.id from tblX x where name like N'%test%')
delete from tblD where id in (select x.id from tblX x where name like N'%test%')

มีวิธีประกาศรายการที่เก็บรหัสจากคำสั่ง select ด้านบนหรือไม่?

ฉันเหนื่อย:

declare @ids int
set @ids = select x.id from tblX x where name like N'%test%'

แต่มันบ่นว่า

แบบสอบถามย่อยส่งคืนค่ามากกว่า 1 ค่า สิ่งนี้ไม่ได้รับอนุญาตเมื่อแบบสอบถามย่อยตามหลัง =, !=, ‹, ‹= , >, >= หรือเมื่อแบบสอบถามย่อยถูกใช้เป็นนิพจน์

กรุณาแนะนำด้วยขอบคุณ


person Eddie    schedule 22.02.2013    source แหล่งที่มา
comment
ลองคิดดูว่าเหตุใดอันดับ 1 จึงใช้งานได้ stackoverflow.com/ คำถาม/11232751/   -  person Tim    schedule 22.02.2013


คำตอบ (3)


คุณจะต้องมีตารางอยู่แล้ว แต่อย่างน้อยคุณก็หลีกเลี่ยงการประมวลผลมากมายโดยทำสิ่งที่คล้ายกันทุกครั้ง:

-- create a table variable
declare @ids table
(
  id int not null
)

-- insert the id into the table variable
insert into @ids
select id from table1 where column1 like '%something%'

-- delete
delete from tablen where id in (select * from @ids)

คุณยังสามารถใช้ตารางชั่วคราวได้ ซึ่งดูเหมือนว่าจะเหมือนกัน แต่แทนที่จะใช้ @ids คุณจะต้องมี #ids และคุณจะต้องละทิ้งตารางชั่วคราวหลังจากงานเสร็จสิ้น

ในการเลือกระหว่างตารางชั่วคราว (ตารางจริง) หรือตัวแปรตาราง (หน่วยความจำเช่นตาราง) คุณจะต้องทำการทดสอบบางอย่างจริงๆ แต่ตามคำจำกัดความแล้ว ข้อมูลที่ซับซ้อนจะทำงานได้ดีกว่าในตารางชั่วคราว หากคุณต้องการเก็บรหัสจำนวนเล็กน้อยในช่วงเวลาสั้น ๆ ฉันมั่นใจมากว่าตัวแปรตารางจะดีกว่า

ความแตกต่างระหว่างอุณหภูมิคืออะไร ตารางและตัวแปรตารางใน SQL Server หรือไม่

person lolol    schedule 22.02.2013
comment
ตัวแปรตารางไม่ใช่เฉพาะหน่วยความจำเท่านั้น นั่นเป็นตำนาน สำหรับความแตกต่างที่ไม่ใช่ตำนาน โปรดดูที่ คำตอบของฉันที่นี่ - person Martin Smith; 23.02.2013
comment
ฉันไม่ได้ตั้งใจอย่างนั้นจริงๆ และยังโพสต์ลิงก์ไปยังความแตกต่างด้วย - person lolol; 25.02.2013

คุณสามารถประกาศตารางชั่วคราว จากนั้นเลือกรหัสที่คุณจะลบลงในตารางนั้น

CREATE TABLE #IDS_from_tblA (id int)
INSERT INTO #IDS_from_tblA(id)
    SELECT x.id FROM tblA WHERE x.id in (select x.id from tblX x where name like N'%test%')
delete from tblA where id in (select x.id from tblX x where name like N'%test%')

(Do whatever you want to do with the ids)

DROP TABLE #IDS_from_tblA 
person Narnian    schedule 22.02.2013

ในเซิร์ฟเวอร์ sql 2008+

declare @IdList table (Id int primary key)

insert into @IDList (Id)
select x.id from tblX x where name like N'%test%'

delete from tblA where id in (select x.id from @IDList x)

หากคุณมีบันทึกมากกว่าร้อยรายการ คุณสามารถใช้ตารางชั่วคราวแทนตัวแปรตารางได้

person Morzel    schedule 22.02.2013