我有一个包含2列的表。第一个是ID,第二个是与该ID相关的SQL SELECT语句。我需要的是一些可以解析每一行并将每个SELECT语句转换为输出的函数或过程。
我正在使用MS SQL Server 2016
示例 表格名称:测试
|-----------|---------------------------------------------------------- |
| ID | SQL |
|-----------|-----------------------------------------------------------|
| 1 | SELECT COUNT(*) FROM dbo.Example WHERE SomeFilter = 'A' |
|-----------|-----------------------------------------------------------|
| 2 | SELECT COUNT(*) FROM dbo.Example WHERE SomeFilter = 'B' |
|-----------|-----------------------------------------------------------|
我可以使用下面的代码每行获得一个结果,但我正在寻找一种可以处理整个表并为每个条目输出结果的过程
DECLARE @SQL NVARCHAR(MAX)
SET @SQL = (SELECT [SQL] FROM [dbo].[Test])
EXECUTE sp_executesql @SQL
所需的输出
|-----------|---------------------------------------------------------- |--------------|
| ID | SQL | Output |
|-----------|-----------------------------------------------------------|--------------|
| 1 | SELECT COUNT(*) FROM dbo.Example WHERE SomeFilter = 'A' | |
|-----------|-----------------------------------------------------------|--------------|
| 2 | SELECT COUNT(*) FROM dbo.Example WHERE SomeFilter = 'B' | |
|-----------|-----------------------------------------------------------|--------------|
像这样可能吗? 如果是,则不胜感激。如前所述,我可以每行逐行获得临时结果,但是需要一种自动方法来解析整个表并返回包含每个SQL查询结果的额外列。
谢谢
答案 0 :(得分:1)
您可以使用Gordon提到的简单循环机制。
DECLARE @ID INT = 1
DECLARE @MAXID INT = (SELECT MAX(ID) FROM dbo.Test)
DECLARE @SQL NVARCHAR(MAX)
CREATE TABLE #TMP (count_records INT, id_from_source INT)
WHILE @ID <= @MAXID
BEGIN
SELECT @SQL = (SELECT SQL FROM Test WHERE ID = @ID)
IF @SQL IS NOT NULL
BEGIN
INSERT #TMP (count_records)
EXECUTE sp_executesql @SQL
UPDATE #TMP SET id_from_source = @ID WHERE id_from_source IS NULL
END
SET @ID = @ID + 1
END
SELECT * FROM #TMP
答案 1 :(得分:1)
希望这就是您要的
Create Procedure gen_SQL_STM
AS
DECLARE @stmList CURSOR;
DECLARE @id varchar(max);
DECLARE @sql varchar(max);
DECLARE @counts int;
BEGIN
SET @stmList = CURSOR FOR
SELECT stm.id, stm.sqlCol
from testTable stm
OPEN @stmList
FETCH NEXT FROM @stmList
INTO @id, @sql
WHILE @@FETCH_STATUS = 0
BEGIN
EXECUTE sp_executesql @sql= @counts OUTPUT
INSERT INTO testTable2(id, sqlstm, MYoutput_count)
SELECT @id, @sql, @counts
FETCH NEXT FROM @stmList
INTO @id, @sql
END;
CLOSE @stmList ;
DEALLOCATE @stmList;
END;
GO