SQL - 插入由nvarchar

时间:2015-10-08 16:15:17

标签: sql sql-server stored-procedures

我的数据库中有几个表格格式为PREFIX_FeatureName。例如:

  • Processed_CallingCountry(featureName nvarchar(max)null,escalatedCount int null,featureValue nvarchar(max)null,RequestNumber int null)

  • Processed_CallingCity(featureName nvarchar(max)null,escalatedCount int null,featureValue nvarchar(max)null,RequestNumber int null)

    [...]

目前,每个表都有一个存储过程,用于计算该功能,并将其插入到正确的表中。每个功能的处理代码几乎相同,功能名称不同。

示例:

SELECT
    (SELECT SUM(IsSpecial) 
     FROM [dbo].[FeaturesBase] 
     WHERE CreatedTime < a.CreatedTime 
       AND CallingCountry = a.CallingCountry ) AS EscalatedCount,
    'CallingCountry' AS FeatureName,
    RequestNumber,
    CallingCountry AS FeatureValue
FROM 
    [dbo].[CssFeaturesBase] a

此代码针对所有功能进行了复制粘贴,仅更改了功能名称 - 在前面的示例中,&#39; CallingCountry&#39;将被其他字符串替换,每个存储过程一个。

有没有办法创建一个将字符串作为输入的单个存储过程,并使用字符串/ nvarchar作为参数进行计算?

基本上,我该怎么做:

CREATE PROCEDURE process (@featureName nvarchar(max))
AS 
BEGIN
    SELECT INTO ('Processed' + @featureName)  -- use the table defined by the string
        (SELECT SUM(IsSpecial) 
         FROM [dbo].[FeaturesBase] 
         WHERE CaseCreatedTime < a.CaseCreatedTime 
           AND @featureName = a.@featureName) AS EscalatedCount,  --use @featureName as column name
        @featureName AS FeatureName,   --use the string literal here
        RequestNumber,
        @featureName AS FeatureValue  --select the proper value
    FROM
        [dbo].[FeaturesBase] a

2 个答案:

答案 0 :(得分:3)

您可能可以使用动态SQL来解决这个问题:

这样的东西
CREATE PROCEDURE process (@featureName nvarchar(max))
AS 
BEGIN

    declare @sql nvarchar(max);

    SET @sql = 'SELECT INTO (Processed_'+ @featureName + ') 
        (SELECT SUM(IsSpecial) FROM [dbo].[FeaturesBase] where CaseCreatedTime < a.CaseCreatedTime AND ' + @featureName +' =  a.'+ @featureName+ ')  as EscalatedCount,  
        '''+@featureName+''' AS FeatureName,
        RequestNumber,
        ' + @featureName + ' AS FeatureValue 
    from [dbo].[FeaturesBase] a'

    exec(@sql);
End

我已经测试了这个,它应该执行以下

SELECT INTO (Processed_CallingCountry) 
        (SELECT SUM(IsSpecial) FROM [dbo].[FeaturesBase] where CaseCreatedTime < a.CaseCreatedTime AND CallingCountry =  a.CallingCountry)  as EscalatedCount,  
        'CallingCountry' AS FeatureName,
        RequestNumber,
        CallingCountry AS FeatureValue 
    from [dbo].[FeaturesBase] a

您应该可以在https://msdn.microsoft.com/en-GB/library/ms188001.aspx

找到更多信息

答案 1 :(得分:0)

在讨论如何插入数据之前,需要解决一些问题:

  1. 为什么featureNameNVARCHAR(MAX)?它会有超过4000个字符吗?我怀疑它应该更接近NVARCHAR(20)
  2. 为什么featureName允许NULL?不应该是NOT NULL
  3. featureName字段很可能甚至不在这些表格中。您需要一个名为Feature的查找表,其中包含FeatureID INT NOT NULL PRIMARY KEYFeatureName NVARCHAR(20) NOT NULL。然后,这些其他表只有FeatureID INT字段和定义引用Feature(FeatureID)的外键。
  4. 您很可能不需要针对不同功能的单独表格?它们具有完全相同的结构,并且您已经有一个字段(即featureName)来区分行。为什么不只有一个Processed表,其中包含以下字段:(FeatureID INT NOT NULL, escalatedCount int null, featureValue nvarchar(max) null, RequestNumber int null)