我正在尝试构建一个尽可能动态的存储过程:
我希望将select语句的值作为可以具有可变数量参数的参数传递,然后通过这些参数执行选择,例如,
select @column1, @column5, @column8 from myTable
@column1, @column5, @column8
- 这些应该作为一个参数传递给存储过程,其中参数的数量可以变化。
如何编写这种存储过程?
答案 0 :(得分:2)
CREATE PROCEDURE usp_selectColumns
@Var1 SYSNAME = NULL
,@Var2 SYSNAME = NULL
,@Var3 SYSNAME = NULL
,@Var4 SYSNAME = NULL
AS
BEGIN
SET NOCOUNT ON;
DECLARE @Columns NVARCHAR(MAX);
DECLARE @Sql NVARCHAR(MAX);
SET @Columns = ', '
+ CASE WHEN @Var1 IS NOT NULL THEN QUOTENAME(@Var1) + N', ' ELSE N' ' END
+ CASE WHEN @Var2 IS NOT NULL THEN QUOTENAME(@Var2) + N', ' ELSE N' ' END
+ CASE WHEN @Var3 IS NOT NULL THEN QUOTENAME(@Var3) + N', ' ELSE N' ' END
+ CASE WHEN @Var4 IS NOT NULL THEN QUOTENAME(@Var4) + N', ' ELSE N' ' END
SET @Columns = LEFT(STUFF(@Columns, 1, 2,''), LEN(STUFF(@Columns, 1, 2,'')) -1)
SET @Sql = N'SELECT ' + @Columns + ' FROM dbo.TableName'
EXECUTE sp_executesql @Sql
END
CREATE TYPE dbo.ColumnNames AS TABLE
(
ColumnName SYSNAME
)
GO
CREATE PROCEDURE usp_selectColumns_TVP
@ColumnName AS dbo.ColumnNames READONLY
AS
BEGIN
SET NOCOUNT ON;
DECLARE @Columns NVARCHAR(MAX);
DECLARE @Sql NVARCHAR(MAX);
SELECT @Columns = STUFF((SELECT ', ' + QUOTENAME(ColumnName)
FROM @ColumnNames
FOR XML PATH(''),TYPE)
.value('.','NVARCHAR(MAX)'),1,2,'')
SET @Sql = N'SELECT ' + @Columns + ' FROM dbo.TableName'
EXECUTE sp_executesql @Sql
END