Sql-Server

SQL Server 中的儲存過程,它返回表中的列總數和每列中值的不同計數

  • March 13, 2020

我需要一個儲存過程,它將任何表名作為參數,並在執行時返回該特定表的每一列中的總行數和不同的值計數。

讓我們以下面的範例表為例:

create table journey
(
   Src varchar(255),  
   Dest varchar(255)
)

insert into journey 
values ('Jaipur', 'Mumbai'), ('Mumbai', 'Jaipur'), ('Kolkata', 'Bangalore'), 
      ('Bangalore', 'Indore'),('Indore', 'Lucknow'), ('Lucknow', 'Indore')

任何人都可以幫助我完成這項動態 SQL 任務。

我進行了一次嘗試,但未給出結果,但在特定表名固定後成功執行。任何人都可以建議程式碼滯後的地方嗎?

create procedure test @table_name varchar(255)
AS

BEGIN 

SELECT count(*) as [Number of columns]
FROM information_schema.columns
WHERE table_name = '@table_name'



SELECT @table_name = 
    Replace( 
      'SELECT ' + SUBSTRING((SELECT ',' +'COUNT(DISTINCT(' + column_name + ')) As ' 
      + column_name + ' ' + CHAR(13) + CHAR(10) 
      FROM information_schema.columns 
      WHERE table_name = '@table_name' 
      for xml path('')),2,200000) + 'FROM @table_name','
','')
exec(@table_name)

END

exec test @table_name = "journey";

像這樣的簡單連接不需要FOR XML PATH,請使用sys.columnsand sp_executesql,我認為您過度使用了table_nameand@table_name一點點。

CREATE PROCEDURE dbo.test   -- always use schema prefix
 @table_name nvarchar(255) -- object names need to be nvarchar
AS
BEGIN
 SET NOCOUNT ON;

 IF OBJECT_ID(@table_name) IS NOT NULL -- protect yourself from SQL injection
 BEGIN
   DECLARE @sql nvarchar(max) = N'SELECT TotalCount = COUNT(*)';

   SELECT @sql += N',' + QUOTENAME('DISTINCT ' + name) 
                + N' = COUNT(DISTINCT ' + QUOTENAME(name) + N')'
     FROM sys.columns 
     WHERE object_id = OBJECT_ID(@table_name)
     -- AND max_length <> -1; -- you may need this on some versions to omit MAX types

   SET @sql += N' FROM ' + @table_name + N';';

   EXEC sys.sp_executesql @sql;
 END
END
GO

進一步閱讀:

引用自:https://dba.stackexchange.com/questions/261874