我写了一个SP,它将表名作为参数并选择一些值并计算它。我的SP如下: -
ALTER PROCEDURE [dbo].[usp_Get_MessageType_And_Count]
@table_name varchar(max)
AS
BEGIN
DECLARE @ActualTableName AS NVarchar(255)
SELECT @ActualTableName = QUOTENAME( TABLE_NAME )
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = @table_name
DECLARE @sql AS NVARCHAR(MAX)
SELECT @sql =
'select [MessageType],count([MessageType]) as Count
from
(SELECT Split.a.value(''.'+','+ 'VARCHAR(100)'') AS [MessageType]
FROM (SELECT [Message Type],
CAST ('+'<M>'+' + REPLACE([Message Type], '+','+', '+'</M><M>'+') + '+'<M>'+' AS XML) AS [MessageType]
FROM ' + @table_name +') AS A CROSS APPLY [MessageType].nodes ('+'/M'+') AS Split(a)) as tab group by [MessageType]'
EXEC(@sql)
END
执行存储过程时出现以下错误: -
Msg 102,Level 15,State 1,Line 7语法不正确&#39;&lt;&#39;。
请帮助我,因为我无法找到我做错的地方。任何帮助将不胜感激。在此先感谢!!
答案 0 :(得分:1)
我认为你正在寻找这样的东西:
ALTER PROCEDURE [dbo].[usp_Get_MessageType_And_Count]
@table_name varchar(max)
AS
BEGIN
DECLARE @ActualTableName AS NVarchar(255)
SELECT @ActualTableName = QUOTENAME( TABLE_NAME )
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = @table_name
DECLARE @sql AS NVARCHAR(MAX)
SELECT @sql =
'select [MessageType],count([MessageType]) as Count
from
(SELECT Split.a.value(''.'',''VARCHAR(100)'') AS [MessageType]
FROM (SELECT [Message Type] AS [Message Type CSV],
CAST (''<M>'' + REPLACE([Message Type], '','',''</M><M>'') + ''</M>'' AS XML) AS [MessageType]
FROM ' + @table_name +') AS A CROSS APPLY [MessageType].nodes (''/M'') AS Split(a)) as tab group by [MessageType]'
EXEC(@sql)
END
希望这有帮助。
答案 1 :(得分:1)
使用以下存储过程。当你得到表名时我改变了逻辑,否则它会出错并且我确保列&#34;消息类型&#34;也存在,否则也会导致错误。
ALTER PROCEDURE [dbo].[usp_Get_MessageType_And_Count]
@table_name varchar(max)
AS
BEGIN
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
SET NOCOUNT ON
DECLARE @ActualTableName AS NVARCHAR(255),
@sql AS NVARCHAR(MAX)
SELECT @ActualTableName = t.TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES t
INNER JOIN INFORMATION_SCHEMA.COLUMNS c
ON t.TABLE_NAME = c.TABLE_NAME
WHERE t.TABLE_NAME = @table_name
AND c.COLUMN_NAME = 'Message Type'
IF (@ActualTableName IS NOT NULL)
BEGIN
SELECT @sql =
'SELECT [MessageType],
COUNT([MessageType]) as CountValue
FROM
(
SELECT Split.a.value(''.'', ''VARCHAR(100)'') AS [MessageType]
FROM (SELECT CAST (''<M>'' + REPLACE([Message Type], '','', ''</M><M>'') + ''</M>'' AS XML) AS [MessageType]
FROM ' + @ActualTableName + '
) AS A
CROSS APPLY [MessageType].nodes (''/M'') AS Split(a)) AS tab
GROUP BY [MessageType]'
EXEC(@sql)
END
ELSE
BEGIN
SELECT 'Table/column does not exist' AS [Message]
END
END