必须声明标量变量错误

时间:2013-08-29 08:35:16

标签: sql-server tsql

这与我的上一个问题有关。我有这段代码:

DECLARE @PatientId UNIQUEIDENTIFIER
DECLARE @FormId NCHAR(16)
DECLARE @columns VARCHAR(8000)
DECLARE @query VARCHAR(8000)

SET @PatientId = '3387F956-EA0A-4660-8647-1096E25A3C6F'
SET @FormId = 'form111'

SELECT @columns = COALESCE(
        @columns + ',[' + RTRIM(AttributeGroup) + '_' + RTRIM(AttributeId) + ']',
        '[' + RTRIM(AttributeGroup) + '_' + RTRIM(AttributeId) + ']'
    )
FROM DVItems
WHERE PatientId = @PatientId AND FormId = @FormId
GROUP BY AttributeGroup, AttributeId

SET @query = '
SELECT * 
FROM( 
    SELECT
        PatientId,
        RTRIM(AttributeGroup) + ''_'' + RTRIM(AttributeId) AS ColName,
        FormId,
        Description
    FROM DVItems
    WHERE PatientId = @PatientId AND FormId = @FormId
) p
PIVOT
(
    MAX(Description)
    FOR [ColName]
    IN (' + @columns + ')
) AS p'

EXECUTE (@query)

当我执行此操作时。它说“必须声明标量变量”@PatientId“。”但是当我注释掉@PatientId和@FormId的I SET值并执行它时,它表示“Command(s)已成功完成”。有帮助吗?谢谢。试试这个fiddle

2 个答案:

答案 0 :(得分:7)

尝试更改此声明 -

SELECT @query = '
SELECT * 
FROM( 
    SELECT
        PatientId,
        RTRIM(AttributeGroup) + ''_'' + RTRIM(AttributeId) AS ColName,
        FormId,
        Description
    FROM dbo.DVItems
    WHERE PatientId = ''' + CAST(@PatientId AS VARCHAR(36)) + ''' 
        AND FormId = ''' + @FormId + '''
) p
PIVOT
(
    MAX(Description)
    FOR [ColName] IN (' + @columns + ')
) AS p'

完整示例 -

DECLARE 
      @PatientId UNIQUEIDENTIFIER
    , @FormId NCHAR(16)
    , @columns VARCHAR(MAX)
    , @query NVARCHAR(MAX)

SELECT 
      @PatientId = '3387F956-EA0A-4660-8647-1096E25A3C6F'
    , @FormId = 'form111'

SELECT @columns = STUFF((
    SELECT DISTINCT ', [' + RTRIM(AttributeGroup) + '_' + RTRIM(AttributeId) + ']'
    FROM dbo.DVItems
    WHERE PatientId = @PatientId
        AND FormId = @FormId
    FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)'), 1, 2, '')

SELECT @query = '
SELECT * 
FROM( 
    SELECT
        PatientId,
        RTRIM(AttributeGroup) + ''_'' + RTRIM(AttributeId) AS ColName,
        FormId,
        Description
    FROM dbo.DVItems
    WHERE PatientId = ''' + CAST(@PatientId AS VARCHAR(36)) + ''' 
        AND FormId = ''' + @FormId + '''
) p
PIVOT
(
    MAX(Description)
    FOR [ColName] IN (' + @columns + ')
) AS p'

EXEC sys.sp_executesql @query

输出 -

PatientId                            FormId           test_01       test_02      test_03
------------------------------------ ---------------- ------------- ------------ ------------
3387F956-EA0A-4660-8647-1096E25A3C6F form111          Test only     Test only    Test only

答案 1 :(得分:0)

喜欢这个

SqlCommand comb = new SqlCommand("INSERT INTO [Bolum] ([Id],[BolumId],[FakulteId], [Ad]) VALUES ('"+id+"','"+bolumid+"','"+fakulteid+"','"+txbAd.Text+"')", conb);