为什么这个 sql select 语句会丢失 varchar 长度,我该如何重新指定它?

Why does this sql select statement lose the varchar length and how do I re-specify it?

我有一个 select 语句,它使用一个数据透视表聚合一些数据,列出一行中一个 ID 的多行数据。现在,虽然我遇到的问题不是让任何东西倒塌或失败,但我想知道为什么被旋转的 varchar(75) 字段的长度正在丢失 varchar 长度。这是我的查询:

SELECT MainID
 , [1] AS InvestigationMethod1    --THIS HAS NO LENGTH
 , [2] AS InvestigationMethod2    --THIS HAS NO LENGTH
 , [3] AS InvestigationMethod3    --THIS HAS NO LENGTH
 , [4] AS InvestigationMethod4    --THIS HAS NO LENGTH
 , [5] AS InvestigationMethod5    --THIS HAS NO LENGTH
 , CASE
     WHEN [6] IS NOT NULL THEN
       'True'
     ELSE
       'False'
   END AS InvestigationFlag
FROM
  (SELECT MainID
    , row_number() OVER (PARTITION BY MainID ORDER BY MainID, GeneralInvestigationMethod.LookupInvestigationMethodID) AS 'RowNumber'
    , InvestigationMethods    --THIS IS OF DATA TYPE varchar(75)
FROM
 GeneralInvestigationMethod
 LEFT OUTER JOIN LookupInvestigationMethod
   ON GeneralInvestigationMethod.LookupInvestigationMethodID = LookupInvestigationMethod.LookupInvestigationMethodID) AS InvestigationMethodSource
PIVOT (max(InvestigationMethodName) FOR [RowNumber] IN ([1], [2], [3], [4], [5], [6])) AS InvestigationMethodPivot

请查看我在查询中的评论,指定相关的确切字段。评论“--THIS IS OF DATA TYPE varchar(75)”旁边的字段如我所说,长度为 75,但是当它旋转时,上述字段:[1]、[2]、[3]、等等。它们失去了长度并显示为没有特定长度的 varchar。为什么会发生这种情况以及如何为这些新字段指定长度?请帮忙,他们在我的 SSIS 包中发出警告,我很乐意解决这个问题。

不确定您为什么会看到这种行为,但我确实为您提供了解决方法:

SELECT MainID
     , Cast([1] As varchar(75)) As InvestigationMethod1
     , Cast([2] As varchar(75)) As InvestigationMethod2
     , Cast([3] As varchar(75)) As InvestigationMethod3
     , Cast([4] As varchar(75)) As InvestigationMethod4
     , Cast([5] As varchar(75)) As InvestigationMethod5
...

只需使用显式 Cast()!

强制使用您想要的数据类型