DECLARE @H_TS MONEY
DECLARE @CLASS VARCHAR(50)='CLASS 04'
DECLARE @TAB_NA VARCHAR(1000)='Classdata'
SET @SQL = 'SELECT @H_TS=SUM(CAST([HISTORY TOTAL$] AS MONEY)) FROM '+@TAB_NA+' WHERE SUBCLASS!=''TOTAL'' AND CLASS LIKE '+@CLASS+''
EXECUTE SP_EXECUTESQL @SQL, N'@H_TS nvarchar(200) OUTPUT', @H_TS = @H_TS OUTPUT
PRINT @H_TS
我收到以下错误
Msg 102,Level 15,State 1,Line 1 '04'附近的语法不正确。
因为我的变量类包含空格有没有办法解决这个问题而不改变类值(不删除类中的空格)
答案 0 :(得分:1)
我认为你只是缺少几个单引号:
SET @SQL = 'SELECT @H_TS=SUM(CAST([HISTORY TOTAL$] AS MONEY)) FROM '+@TAB_NA+'
WHERE SUBCLASS!=''TOTAL'' AND CLASS LIKE ''' + @CLASS + ''''
EXECUTE SP_EXECUTESQL @SQL, N'@H_TS nvarchar(200) OUTPUT', @H_TS = @H_TS OUTPUT
答案 1 :(得分:0)
假设您正在尝试执行LIKE查询并需要您的%运算符,这可能就是您要查找的内容:
CREATE TABLE ClassData ([History Total$] int, SUBCLASS varchar(100), class varchar(100));
INSERT INTO ClassData VALUES (1, 'TOTAL', '1Class 04');
INSERT INTO ClassData VALUES (2, 'NOTTOTAL', '1Class 04 22');
DECLARE @H_TS MONEY
DECLARE @CLASS VARCHAR(50)='CLASS 04'
DECLARE @TAB_NA VARCHAR(1000)='Classdata'
DECLARE @SQL NVARCHAR(MAX);
SET @SQL = 'SELECT @H_TS=SUM(CAST([HISTORY TOTAL$] AS MONEY)) FROM '+@TAB_NA+' WHERE SUBCLASS!=''TOTAL'' AND CLASS LIKE ''%' + @CLASS + '%''';
EXECUTE SP_EXECUTESQL @SQL, N'@H_TS nvarchar(200) OUTPUT', @H_TS = @H_TS OUTPUT
SELECT @H_TS
DROP TABLE ClassData
祝你好运。