SQL迭代选择语句

时间:2018-02-01 10:28:44

标签: sql sql-server

在我的数据库中,我有各种Schemas&每个Schema都有一个表[Company]&其他表格。

我在下面写了Query,它迭代所有的Schema&如果我想在表格中INSERT为所有模式运行此查询。

我陷入了一个场景,其中插入查询需要[Company]表中的值。

示例 - 在1个架构中我有[Company]表&我有4个记录。 所以我希望在INSERT表格中[Menu] 4条记录公司ID将从[Company]表格中挑选。

现在,在下面的查询中,我只是从[Company]表中选择ID。 我想知道如何遍历Select Statement的记录?

-- in-memory schema table to hold distinct schema_names
DECLARE @i int
DECLARE @numrows int
DECLARE @schema_names nvarchar(max)
DECLARE @schema_table TABLE (
    idx smallint Primary Key IDENTITY(1,1)
    , schema_names nvarchar(max)
)
DECLARE @company_table nvarchar(max)
DECLARE @sql nvarchar(max)


-- populate schema table
INSERT @schema_table
SELECT name FROM sys.schemas Where name <> 'dbo' AND name <> 'guest' AND name <> 'INFORMATION_SCHEMA' AND name <> 'db_accessadmin' AND name <> 'db_backupoperator' AND name <> 'db_datareader' AND name <> 'db_datawriter' AND name <> 'db_ddladmin' AND name <> 'db_denydatareader' AND name <> 'db_denydatawriter' AND name <> 'db_owner' AND name <> 'db_securityadmin' AND name <> 'sys'

select * from @schema_table
-- enumerate the table

SET @i = 1
SET @numrows = (SELECT COUNT(*) FROM @schema_table)
IF @numrows > 0
    WHILE (@i <= (SELECT MAX(idx) FROM @schema_table))
    BEGIN

        -- get the next record primary key
        SET @schema_names = (SELECT schema_names FROM @schema_table WHERE idx = @i)
        SET @company_table = '['+@schema_names+'].[Company]' 
        SET @sql = 'select Id from ' + @company_table
        EXEC(@sql)

        BEGIN TRY
            DECLARE @sSQL nvarchar(500);            
            SELECT @sSQL = N'INSERT ['+@schema_names+'].[Menu] VALUES (9, N''Dashboard'', N''Charts'', N''/Dash/Chart'', 1)'
            EXEC sp_executesql @sSQL
        END TRY
        BEGIN CATCH
            SELECT ERROR_MESSAGE()+' '+@schema_names AS ErrorMessage;
        END CATCH

        -- increment counter for next record
        SET @i = @i + 1
    END

在此查询中 - 9将被[公司]表中的值替换。

2 个答案:

答案 0 :(得分:1)

只需简单地在每行中进行迭代,就可以使用下面的示例

CREATE PROCEDURE cursor1()
BEGIN
DECLARE finished INTEGER DEFAULT 0;
DECLARE fname1 CHAR(20) DEFAULT "";
DECLARE lname1 CHAR(20) DEFAULT "";
DECLARE nameList CHAR(100) DEFAULT "";
-- 1. Declare cursor for employee
DECLARE emp_cursor CURSOR FOR SELECT fname, lname FROM employee WHERE salary > 40000;
-- 2. Declare NOT FOUND handler
DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
-- 3. Open the cursor
OPEN emp_cursor;
L: LOOP
-- 4. Fetch next tuple
FETCH emp_cursor INTO fname1, lname1;
-- Handler will set finished = 1 if cursor is empty
IF finished = 1 THEN
LEAVE L;
END IF;
-- build emp list
SET nameList = CONCAT( nameList, fname1, ' ', lname1, ';' );
END LOOP ;
-- 5. Close cursor when done
CLOSE emp_cursor;
SELECT nameList ;
END //
DELIMITER

答案 1 :(得分:0)

为Eg2。

DROP PROCEDURE IF EXISTS depreciation_calculator;
# depreciation calculator..........................................
CREATE PROCEDURE depreciation_calculator(IN deprcesionDate INT)
  BEGIN
    DECLARE acc DOUBLE;
    DECLARE diff INT;
    DECLARE currentDate DATE;
    DECLARE depDate VARCHAR(12);
    DECLARE dep DOUBLE;
    DECLARE bookValue DOUBLE;
    DECLARE assetId INT;
    DECLARE depStatus VARCHAR(12);
    DECLARE finished INTEGER DEFAULT 0;
    DECLARE emp_cursor CURSOR FOR SELECT
                                    dep_date,
                                    dep_amount,
                                    dep_status,
                                    asset_ass_id,
                                    book_value,
                                    accumulative_value
                                  FROM depreciation;
    -- 2. Declare NOT FOUND handler
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
    -- 3. Open the cursor
    OPEN emp_cursor;
    L: LOOP
      -- 4. Fetch next element
      FETCH emp_cursor
      INTO depDate, dep, depStatus, assetId, bookValue, acc;
      -- Handler will set finished = 1 if cursor is empty
      IF finished = 1
      THEN
        LEAVE L;
      END IF;
      SET currentDate = DATE(now());
      SET diff := TIMESTAMPDIFF(MONTH, depDate, currentDate);


      IF diff > 12 && diff <= 13 && bookValue > 0
      THEN
        SET depDate = currentDate;
        SET dep = dep;
        SET acc = acc + dep;
        SET bookValue = bookValue - dep;
        IF bookValue = 0
        THEN
          SET depStatus = 'depreciated';
        END IF;
        INSERT INTO depreciation (dep_date, dep_amount, dep_status, dep_description, dep_commnet, asset_ass_id, book_value, accumulative_value)
        VALUES (depDate, dep, depStatus, 1, 1, assetId, bookValue, acc);
      END IF;
    END LOOP;
    -- 5. Close cursor when done
    CLOSE emp_cursor;
    SELECT diff;
  END;