存储过程 - 变量声明和类型出错

时间:2014-04-16 13:48:58

标签: sql-server stored-procedures

CREATE PROCEDURE AP_ModelingDataset_Creation1
    @Product varchar(max),
    @Segment varchar(max)
as
Begin
Declare @query2 nvarchar(max)

Declare @Responders_Count_query nvarchar(max)
Declare @NonResponders_Count_query nvarchar(max)
Declare @Percentage_query nvarchar(max)
Declare @Responders_Count int
Declare @NonResponders_Count int
Declare @Percentage float


--Oversampling:
set @Responders_Count_query = N'select @Responders_Count=count(*) from AP_'+replace(@Product,' ','_')+'_'+@Segment+'_ModelingDataset_Total where Flag=1'
set @NonResponders_Count_Query = N'select @NonResponders_Count = count(*) from AP_'+replace(@Product,' ','_')+'_'+@Segment+'_ModelingDataset_Total where Flag=0'
set @Percentage_Query = N'select @Percentage = ((@Responders_Count)*(10.0))/(@NonResponders_Count)'

set @query2 =
'SELECT s.*
into AP_'+replace(@Product,' ','_')+'_'+@Segment+'_ModelingDataset
FROM
(
SELECT *
from AP_'+replace(@Product,' ','_')+'_'+@Segment+'_ModelingDataset_Total
where Flag=1
UNION
SELECT *
FROM AP_'+replace(@Product,' ','_')+'_'+@Segment+'_ModelingDataset_Total
WHERE Flag=0 AND 
(SELECT '+@Percentage+') >= CAST(CHECKSUM(NEWID(), [MSSalesTPID]) & 0x7fffffff AS float) / CAST (0x7fffffff AS int)
)s' 

EXEC sp_executesql @Responders_Count_query, N'@Responders_Count int OUTPUT', @Responders_Count OUTPUT;
EXEC sp_executesql @NonResponders_Count_query, N'@NonResponders_Count int OUTPUT', @NonResponders_Count OUTPUT;
EXEC sp_executesql @Percentage_query, N'@Percentage float OUTPUT', @Percentage OUTPUT;
exec(@query2)

END
GO

此存储过程运行,但会引发错误

  

必须声明标量变量@responders_count

1 个答案:

答案 0 :(得分:1)

您正在尝试将float值连接到字符串

更改

(SELECT '+@Percentage+') >= CAST(CHECKSUM(NEWID(), [MSSalesTPID]) & 0x7fffffff AS float) / CAST (0x7fffffff AS int)
)s' 

(SELECT '+convert(varchar,@Percentage)+') >= CAST(CHECKSUM(NEWID(), [MSSalesTPID]) & 0x7fffffff AS float) / CAST (0x7fffffff AS int)
)s'