gpt4 book ai didi

sql - 如何使用 SQL 创建多个存储过程

转载 作者:行者123 更新时间:2023-12-02 06:45:56 25 4
gpt4 key购买 nike

我有一个 vb.net 函数,它根据传递给函数的参数创建多个存储过程。

我想将此 vb.Net 移动到单个 SQL 文件中(出于维护原因),但我不确定如何在不创建 7 个单独的存储过程的情况下在 SQL 中重新创建它。

我总共创建了 20 个存储过程,我真的不想在 SQL 文件中创建这么多,因为维护将是一场噩梦。我想知道是否有类似于我在下面的 VB.Net 中所做的解决方案:

Private Sub CreateStoredProcedures()

CreateSP("SummaryNone", "YEAR([sale].[DateTime])")
CreateSP("SummaryUser", "[sale].[User]")
CreateSP("Summarysale", "[sale].[sale]")
CreateSP("SummaryBatch", "[sale].[Batch]")
CreateSP("SummaryDay", "dbo.FormatDateTime([sale].[DateTime], 'yyyy-mm-dd')")
CreateSP("SummaryMonth", "dbo.FormatDateTime(dbo.DateSerial(YEAR([sale].[DateTime]), MONTH([sale].[DateTime]), 1), 'yyyy-mm-dd')")
CreateSP("SummaryYear", "Year([sale].[DateTime])")

Return
End Sub


Private Sub CreateSP(ByVal vName As String, ByVal vGroup As String)

Dim CommandText As String = _
"CREATE PROCEDURE " & vName _
& " @StartDate varchar(50)," _
& " @EndDate varchar(50)" _
& " AS " _
& " SELECT " & vGroup & " AS GroupField," _
& " Sum([Project].[NumProject]) AS TotalProject," _
& " Sum([Project].[Title]) AS SumTitle," _
& " Sum([Project].[Duration]) AS SumDuration," _
& " Sum([Project].[Info]) AS SumInfo," _
& " Sum([Customer].[NumCustomer]) AS TotalNumCustomer," _
& " Sum([Orders].[NumOrders]) AS TotalNumOrders," _
& " Sum([OrderInspection].[NumInspects]) AS TotalNumInspects," _
& " Sum([OrderInspection].[NumFails]) AS TotalNumFails," _
& " Sum([CustomerInspection].[NumInspects]) AS TotalNumCustomerInspectionInspects," _
& " Sum([CustomerInspection].[NumFails]) AS TotalNumCustomerInspectionFails," _
& " Sum([Measurements].[NumMeasurements]) AS TotalNumMeasurementss" _
& " FROM ((((((sale LEFT JOIN Project ON [sale].[saleId]=[Project].[saleId])" _
& " LEFT JOIN Customer ON [Project].[PrintId]=[Customer].[PrintId])" _
& " LEFT JOIN Orders ON [Project].[PrintId]=[Orders].[PrintId])" _
& " LEFT JOIN OrderInspection ON [Project].[PrintId]=[OrderInspection].[PrintId])" _
& " LEFT JOIN CustomerInspection ON [Project].[PrintId]=[CustomerInspection].[PrintId])" _
& " LEFT JOIN Measurements ON [Project].[PrintId]=[Measurements].[PrintId])" _
& " WHERE [sale].[DateTime] BETWEEN dbo.FormatDateTime((@StartDate), 'yyyy-mm-dd')" _
& " AND dbo.FormatDateTime((@Enddate),'yyyy-mm-dd')" _
& " GROUP BY " & vGroup & "" _
& " ORDER BY " & vGroup & ";"

SqlExecuteNonQuery(CommandText)

return
End Sub

期待您的评论和回复。

谢谢

最佳答案

您可以将模板存储在文本文件中,作为 .NET DLL 中的嵌入式资源。为您的动态位设置一些占位符。这将使您当前的解决方案更易于维护。然后从 DLL 加载流并保留当前的实现。

编辑文本文件比嵌入在 C# 文件中的大块 SQL 更容易。

如果将其移至单个过程,您可能会受到性能影响,您可能对此感到满意,但请记住,该过程也会有一些维护问题。我们通常喜欢避免存储过程中的动态 SQL。 7 路 IF 分支是维护的噩梦。

关于sql - 如何使用 SQL 创建多个存储过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/531535/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com