sql - 以表变量为参数执行存储过程
问题描述
有谁知道为什么这个查询不起作用?如何将表变量 itemId 作为参数添加到 exec 语句?谢谢
DECLARE @test TABLE
(
itemId UNIQUEIDENTIFIER,
finalAmount DECIMAL
);
INSERT INTO @test EXEC [GetItems]
DECLARE @sql NVARCHAR(max)
DECLARE @param NVARCHAR(max)
SET @param = N'select itemId from @test'
SELECT @sql = 'EXEC [InsertTestItem]'+' ' + @param;
SELECT @sql
EXEC(@sql)
解决方案
请参阅 SQL Server 中的完整工作示例,您应该能够一个接一个地运行每个块,以查看它从您传递到存储过程的表类型中选择了所有内容
-- Create the Table type that we will use in the stored proc------------------------
IF NOT EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = 'MyIdTableType')
BEGIN
PRINT 'Creating type [dbo].[MyIdTableType]'
CREATE TYPE [dbo].MyIdTableType AS TABLE (
Id BIGINT
)
END
GO
-- Create a stored proc that uses it ------------------------
CREATE PROCEDURE [dbo].[UsMyTabelType]
@IdsTable AS [dbo].MyIdTableType Readonly
AS
BEGIN
-- Now you have the data you can use it like any normal table and join on it
SELECT * FROM @IdsTable
END
GO
-- Lets test it out ------------------------
DECLARE @myIds AS MyIdTableType
INSERT INTO @myIds (Id)
VALUES
(1),
(2),
(3)
EXEC dbo.UsMyTabelType @IdsTable = @myIds
推荐阅读
- python - Django:在模型中创建一个特定于用户的值
- php - 我想在 php 上包含来自网络的代码。示例:需要“domain.com/folder/file.php”;
- javascript - 您可以使用 Crossfilter 在组内过滤吗
- google-apps-script - Google App Script My Project 中的多个文件
- python - Python温度转换器中请求的错误处理帮助
- python - 从“外部”目录导入模块 [Python]
- python - 来自初学者的简单 DataFrame 问题
- vue.js - Vue:导入 JSON 请求加载器
- python - 使用 Pandas Dataframe 时 casefold() 函数不起作用
- c++ - /bin/sh: cc: 找不到命令