SQL Server Exec multiple statements in a cursor based on two list arrays [closed]

wz1wpwve  于 2024-01-05  发布在  其他
关注(0)|答案(1)|浏览(108)

Closed. This question needs details or clarity . It is not currently accepting answers.

Want to improve this question? Add details and clarify the problem by editing this post .

Closed 12 days ago.
Improve this question

I've recently transitioned from Oracle to Microsoft SQL Server and I'm struggling with how to execute multiple statements based on a set of arrays. For instance I have a series of record ID's and another list of values I want to update a column to and perhaps perform an additional action on.

  1. BEGIN
  2. DECLARE List1 ['exampl1', 'example2', 'example3']
  3. DECLARE List2 ['value1', 'value2', 'value3']
  4. DECLARE rcount AS int = 1
  5. OPEN cursor c_whatever
  6. UPDATE tableA
  7. SET colA = "List2.rcount"
  8. WHERE id = "list1.rcount"
  9. DELETE FROM tableB
  10. WHERE id = "list1.rcount" AND columnA = "List2.rcount"
  11. rcount = +1
  12. CLOSE CURSOR c_Whatever
  13. END

Super rudimentary (and not syntactically correct) but I think you'll get the gist of what I'm trying to accomplish.

1u4esq0p

1u4esq0p1#

SQL Server does not have arrays, but it does have temporary tables and table variables that can be used similarly.

One equivalent of your code in SQL Server would be:

  1. DECLARE @List TABLE (
  2. Col1 VARCHAR(100),
  3. Col2 VARCHAR(100)
  4. );
  5. INSERT @List
  6. VALUES
  7. ('exampl1', 'value1'),
  8. ('example2', 'value2'),
  9. ('example3', 'value3');
  10. UPDATE A
  11. SET colA = L.Col2
  12. FROM @List L
  13. JOIN tableA A
  14. ON A.id = L.Col1;
  15. DELETE B
  16. FROM @List L
  17. JOIN tableB B
  18. ON B.id = L.COl1
  19. AND B.columnA = L.COl2;

Here I have combined the two arrays into a single table variable having two columns. That table variable can be used in SELECT, INSERT, UPDATE, and DELETE statements just like any other table, so no cursor is needed.

展开查看全部

相关问题