首页 > 解决方案 > 如何在 SQL Server 中通过 OPENROWSET 或 SomeFunction 选择动态字符串 SQL 结果

问题描述

我的预期查询:

with cte as 
(
    select 'select 1 + 2' tSql 
    union all
    select 'select 1 * 2' tSql
)
select somefunction(tsql) as val
from cte

结果 :

val
3
2

我尝试使用以下方法执行此操作:

  1. 使用开放式设置:

我使用OPENROWSET可以获得动态字符串 SQL 结果

SELECT * 
FROM OPENROWSET('SQLNCLI','Server=(local);Trusted_Connection=yes;','select 1+2') --result : 3

但我得到这个 SQL 错误

消息 7314,级别 16,状态 1,第 1 行
链接服务器“(本地)”的 OLE DB 提供程序“SQLNCLI”不包含表 tSql。该表不存在或当前用户对该表没有权限。

with cte as 
(
    select 'select 1 + 2' tSql 
    union all
    select 'select 1 * 2' tSql
)
select (SELECT * FROM OPENROWSET('SQLNCLI','Server=(local);Trusted_Connection=yes;',tSql)) as val
from cte

我检查了msdn doc得到的问题点是:

在此处输入图像描述

2.使用sp_executesql

create function F_SqlToNumeric(@sql nvarchar(max))
returns numeric(20,8) as 
begin
    declare @v numeric(20,8);
    select @sql = N'select @v_out = ('+@sql+')';
    exec sp_executesql @sql,N'@v_out numeric(20,8) output',@v_out = @v output
    return @v
end;
with cte as 
(
    select 'select 1 + 2' tSql 
    union all
    select 'select 1 * 2' tSql
)
select F_SqlToNumeric(tSql) as val
from cte

我得到错误:

错误 557,只能从函数内执行函数和扩展存储过程。

标签: sqlsql-server

解决方案


推荐阅读