SQL Server Array on Declare statements via query

mmvthczy  于 2023-10-15  发布在  其他
关注(0)|答案(2)|浏览(183)

I am trying to do something like

  1. DECLARE @ID int = CHANGEME,
  2. @StartDate datetime = '2023-09-02 04:00',
  3. @FinishDate datetime = '2023-09-03 04:00'

But this only lets me run this report per id, I have a list of IDs from another table that i can pull by a query

  1. select id
  2. form table
  3. where tablename like '$tryme$'

So is there a way that I can run the report per ID again and again until we've run the list finished?

I saw that this is the way to write multiple/array in the statement

  1. DECLARE @SITEIDS TABLE(siteid int)
  2. Insert into @SITEIDS
  3. values ('R00013'), ('R00028')

but this looks like it's hard coded ids.

I'm trying to get a report with

  1. DECLARE @ID int = 1,
  2. DECLARE @ID int = 12,
  3. DECLARE @ID int = 123,
xvw2m8pv

xvw2m8pv1#

Something like the following should allow you to do exactly what you are asking.

  1. DECLARE @id int;
  2. SELECT @id = MIN(id) FROM table where tablename like '$tryme$'
  3. WHILE @id IS NOT NULL
  4. BEGIN
  5. -- Code to run your report here
  6. SELECT @id = MIN(id) FROM table WHERE tablename like '$tryme$' AND id > @id
  7. END

You put the MIN(id) into your @id variable, process the report for that value, then grab the next MIN(id) that's greater than the one you just processed, and keep looping until no more id value is found.

cgh8pdjw

cgh8pdjw2#

  1. DECLARE @StartDate datetime = '2023-09-02 04:00'
  2. DECLARE @FinishDate datetime = '2023-09-03 04:00'
  3. CREATE TABLE #TempIDs (ID int)
  4. INSERT INTO #TempIDs (ID)
  5. SELECT id FROM YourTable WHERE tablename LIKE '$tryme$'
  6. DECLARE @CurrentID int
  7. SELECT TOP 1 @CurrentID = ID FROM #TempIDs
  8. -- Loop through the IDs and run the report for each ID
  9. WHILE @CurrentID IS NOT NULL
  10. BEGIN
  11. -- Execute your report here using @CurrentID
  12. -- Delete the processed ID from the temporary table
  13. DELETE FROM #TempIDs WHERE ID = @CurrentID
  14. -- Get the next ID
  15. SELECT TOP 1 @CurrentID = ID FROM #TempIDs
  16. END
  17. DROP TABLE #TempIDs
展开查看全部

相关问题