执行select语句的结果

时间:2011-05-17 18:17:25

标签: sql-server executequery

如何执行select查询的结果。下面的查询为我提供了一些SQL语句。我想执行do语句,怎么做?所有这些都在SQL Sever Management Studio中执行。

查询:

SELECT 'UPDATE Rolecopy SET PartofFT = ''' + R2.PlayedbyOT + ''', OriginalOT = ''' + R.PlayedbyOT + ''' WHERE RoleNo = ' + CAST(R.RoleNo AS VARCHAR) + CHAR(13)
FROM Role R INNER JOIN Role R2
ON R.PartofFT = R2.PartofFT AND R.RoleNo <> R2.RoleNo
WHERE EXISTS (
    SELECT PG.RoleNo
    FROM V_PurposeGrouping PG
    WHERE R.PartofFT = PG.PartofFT
    AND R.RoleNo <> PG.RoleNo
)

结果:

UPDATE Rolecopy SET PartofFT = 'Student', OriginalOT = 'Teacher' WHERE RoleNo = 5.00
UPDATE Rolecopy SET PartofFT = 'Project', OriginalOT = 'Teacher' WHERE RoleNo = 8.00
UPDATE Rolecopy SET PartofFT = 'Project', OriginalOT = 'description' WHERE RoleNo = 10.00
UPDATE Rolecopy SET PartofFT = 'Student', OriginalOT = 'Project' WHERE RoleNo = 15.0

0

2 个答案:

答案 0 :(得分:18)

尝试使用第一个查询打开游标,然后在循环中将结果字符串作为动态SQL执行。

declare commands cursor for
SELECT 'UPDATE Rolecopy SET PartofFT = ''' + R2.PlayedbyOT + ''', OriginalOT = ''' + R.PlayedbyOT + ''' WHERE RoleNo = ' + CAST(R.RoleNo AS VARCHAR) + CHAR(13)
FROM Role R INNER JOIN Role R2
ON R.PartofFT = R2.PartofFT AND R.RoleNo <> R2.RoleNo
WHERE EXISTS (
    SELECT PG.RoleNo
    FROM V_PurposeGrouping PG
    WHERE R.PartofFT = PG.PartofFT
    AND R.RoleNo <> PG.RoleNo
)

declare @cmd varchar(max)

open commands
fetch next from commands into @cmd
while @@FETCH_STATUS=0
begin
  exec(@cmd)
  fetch next from commands into @cmd
end

close commands
deallocate commands

答案 1 :(得分:3)

尝试使用:

SELECT 'UPDATE Rolecopy SET PartofFT = ''' + R2.PlayedbyOT + ''', OriginalOT = ''' + R.PlayedbyOT + ''' WHERE RoleNo = ' + CAST(R.RoleNo AS VARCHAR) + CHAR(13)
FROM Role R INNER JOIN Role R2
ON R.PartofFT = R2.PartofFT AND R.RoleNo <> R2.RoleNo
WHERE EXISTS (
    SELECT PG.RoleNo
    FROM V_PurposeGrouping PG
    WHERE R.PartofFT = PG.PartofFT
    AND R.RoleNo <> PG.RoleNo
)
FOR XML PATH ('')

结果将进入一个字符串列:

UPDATE Rolecopy SET PartofFT = 'Student', OriginalOT = 'Teacher' WHERE RoleNo = 5.00
UPDATE Rolecopy SET PartofFT = 'Project', OriginalOT = 'Teacher' WHERE RoleNo = 8.00
UPDATE Rolecopy SET PartofFT = 'Project', OriginalOT = 'description' WHERE RoleNo = 10.00
UPDATE Rolecopy SET PartofFT = 'Student', OriginalOT = 'Project' WHERE RoleNo = 15.0

全部在同一栏中。