使用表变量的其他方法比动态查询

时间:2017-10-10 04:22:55

标签: sql-server sql-server-2008 stored-procedures

我有一个存储过程来计算记录数。

CREATE PROCEDURE spCountAnyTableRows
    (@PassedTableName as NVarchar(255)) 
AS
    -- Counts the number of rows from any non-system Table, *SAFELY*
BEGIN
    DECLARE @ActualTableName AS NVarchar(255)

    SELECT @ActualTableName = QUOTENAME( TABLE_NAME )
    FROM INFORMATION_SCHEMA.TABLES
    WHERE TABLE_NAME = @PassedTableName

    DECLARE @sql AS NVARCHAR(MAX)
    SELECT @sql = 'SELECT COUNT(*) FROM ' + @ActualTableName + ';'

    EXEC(@SQL)
END

现在,我想使用更复杂的查询来替换上面定义的@sql中的简单查询,并且我必须在查询中使用表别名,因为有很多连接。我不知道如何在动态查询中使用表别名。

我的问题:如果有办法使用表别名,还是在存储过程中使用表变量的任何其他方法吗?

2 个答案:

答案 0 :(得分:0)

在动态sql中使用别名是最重要的,为每个表名变量分配别名。

SELECT @ActualTableName = QUOTENAME( TABLE_NAME ) + ' as a'
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = @PassedTableName

确保为同一查询中涉及的表提供唯一的别名。

甚至在动态查询中你可以提供别名

SELECT @sql = 'SELECT COUNT(*) FROM ' + @ActualTableName + ' as a ;'

答案 1 :(得分:0)

/* This Script is use to Fetch To count the Numbers of rows in Table */
CREATE TABLE  #rowcount (tablename VARCHAR(128), cnt INT)
EXEC sp_MSforeachtable
 @command1 = 'Insert into #rowcount select ''?'',
              count(*) from ?',
 @whereand = 'and o.name = ''Table_Name''',   -- Table_Name
 @postcommand = 'SELECT * from #rowcount Where Cnt >0  Order by tablename'

DROP TABLE  #rowcount

OR YOU Can Get All Table Row Count by removing Where clause

CREATE TABLE  #rowcount (tablename VARCHAR(128), cnt INT)
EXEC sp_MSforeachtable
 @command1 = 'Insert into #rowcount select ''?'',
              count(*) from ?',
 @postcommand = 'SELECT * from #rowcount Where Cnt >0  Order by tablename'

DROP TABLE  #rowcount