sql - 如何在 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
我尝试使用以下方法执行此操作:
- 使用开放式设置:
我使用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,只能从函数内执行函数和扩展存储过程。
解决方案
推荐阅读
- vba - 获取特定对象 vba 的库名称
- html - 使用 HTML、CSS 绘制三角形和形状
- c# - 如何使用 CRUD 功能创建连接到数据库的 Blazor WebAssembly 网站
- mysql - 扩展后连接到 apache 的问题,我在 Kubernetes 上的有状态数据库
- angular - 单击角度 12 中的每个 formArray 元素后,如何禁用 formArray 的特定单击事件?
- c++ - How unused default member initializer can change program behavior in C++?
- hibernate - 如何在休眠 4 中使用 Dto 而不是 Model 类
- extjs - 如何从来自 json 的商店上传动态数据
- r - 更改 ggplot-legend 中字形的颜色
- java - 如何直接从protobuf创建GRPC服务器而不将其编译成java代码