尝试编写通用存储过程,该存储过程将归档来自具有不同列的不同表中的数据。如何为存储过程支持多个参数?
我正在从Powershell传递表名,列名和列类型以触发存储过程。我为Powershell声明了最多5个参数,并将它们的值设置为null。如果没有为参数传递任何值,则将其视为null。现在,我必须使用这些参数创建一个临时表,以进一步进行归档。我不能将null值传递给create表。我如何从这里开始?还是有更好的方法来做到这一点?
到目前为止的代码-
配置文件:
<appsettings>
<add key = "NumberOfParameters" value = "2"/>
<add key = "column1" value = "[TradeId] [varchar]"/>
<add key = "column2" value = "[TransactionNumber] [int]">
</appsettings>
Powershell脚本:
$numberOfParameters = [string]$appsettings["NumberOfParameters"]
$nulberofParametersInt =[int]$numberOfParameters
$Columns =@()
for(@j=0;$j -lt $numberOfParametersInt; $j++)
{
$k=$j+1
$stringValue = "Column" +$k
$Column = [string]$appsettings[$stringValue]
$Columns += $Column
}
.
.
.
$SqlCmd.COnnection =$SqlConnection
$SqlCmd.CommandText = "EXEC SP_storedProcedure " + $TableName + " " + $Columns
$Returnvalue = $SqlCmd.ExecuteScalar()
存储过程:
CREATE PROCEDURE [dbo].[SP_storedProcedure]
@tableName as VARCHAR(50),
@Column1 as varchar(50),
@COlumn2 as varchar(50) = null,
@Column3 as varchar(50) = null,
@Column4 as varchar(50) = null,
@Column5 as varchar(50) =null
as
begin
begin try
declare @i int
set @i =0
while(@i<5)
begin
set @String = '@Column' + @i
exec('if (@Column' +@I+' is not null)
set @String = @String +@Column'+@i)
set @i = @i+1
end
EXECUTE('CREATE TABLE #Temp('+@String+)')
INSERT into #Temp () exec('select columns from OriginalTable')