SQL Server中的查询获取大约30个记录,包含15列。我想合并它并将其转换为一条记录中30 * 15 = 450列的记录。但是当我尝试在开始时声明@SqlText
变量时。
以下是示例代码:
DECLARE @SqlText NVARCHAR(MAX) = ''
DECLARE @SqlText NVARCHAR(MAX) = 'select * from ((SELECT 'abc' AS ID,
SUBSTRING(col1,0,10) ID_Mark,
CASE
WHEN (UPPER(SUBSTRING(REPLACE(col2, '0123456789', NULL ), 0, 2 ))='E-')
THEN SUBSTRING(REPLACE(col2, '0123456789', NULL ), 3, 4 ) .......
group by ID, ID_Mark, col1, col2, .....)) PE'
SELECT @SqlText = @SqlText + ' INNER JOIN PE'+ CONVERT(VARCHAR, ID) +'.ID_Mark = ' + CONVERT(VARCHAR, ID_Mark)
FROM PE
order by ID_Mark
SET @SqlText = @SqlText
EXEC (@SqlText)
当我执行此代码时,出现错误
消息208无效对象名称'PE'。
其中PE是查询的表别名。如何解决这类问题?
您收到错误消息,因为在查询字符串中,您给单引号错误。如果要在Query字符串中包含单引号,则应将其指定为2个单引号。
所以如果你想在Query字符串中选择字符串'ABC',你应该这样给它
EXEC('SELECT ''ABC'' AS MyStr')
所以你的查询需要像这样改变
DECLARE @SqlText NVARCHAR(MAX) = 'select * from ((SELECT ''abc'' AS ID,
SUBSTRING(col1,0,10) ID_Mark,
CASE
WHEN (UPPER(SUBSTRING(REPLACE(col2, ''0123456789'', NULL ), 0, 2 ))=''E-'')
THEN SUBSTRING(REPLACE(col2, ''0123456789'', NULL ), 3, 4 ) .......
group by ID, ID_Mark, col1, col2, .....)) PE'
SELECT @SqlText = @SqlText + ' INNER JOIN PE'+ CONVERT(VARCHAR, ID) +'.ID_Mark = ' + CONVERT(VARCHAR, ID_Mark)
FROM PE
order by ID_Mark
SET @SqlText = @SqlText
EXEC (@SqlText)
只需用2个单引号替换每个单引号。