简体   繁体   English

动态选择 where 条件中的列

[英]Choosing column in where condition dynamically

I am new to dynamic SQL programming.我是动态 SQL 编程的新手。 There are a set of tables with different schema (rows and values) whose record count is being taken dynamically through a loop.有一组具有不同模式(行和值)的表,它们的记录计数是通过循环动态获取的。 However, the records which are soft deleted shouldn't be a part of record count.但是,被软删除的记录不应该是记录计数的一部分。 Each of the table has a column which signifies a soft delete in Table_Name_IS_DELETED, for instance TB1_IS_DELETED.每个表在 Table_Name_IS_DELETED 中有一个表示软删除的列,例如 TB1_IS_DELETED。 Please help me in dynamically updating the column name in the where condition.请帮我动态更新 where 条件中的列名。

The code I have written for counts我为计数编写的代码

SET @Query = 'SELECT @K  = COUNT(*) FROM ['+@DB_Source+'].['+@Table_Schema+'].['+@Table_Name+'] x WITH (NOLOCK)

    EXEC sp_executesql @Query, N'@K INT OUTPUT', @K=@K OUTPUT;

Now there should be a WHERE condition in the dynamic query which should be like "TB1_IS_DELETED = 1" and the table name (TB1) should be updated accordingly.现在动态查询中应该有一个WHERE条件,它应该类似于“TB1_IS_DELETED = 1”,并且应该相应地更新表名 (TB1)。

Thanks for your help.谢谢你的帮助。 :) :)

Like this:像这样:

SET @Query = '
SELECT @K = COUNT(*) 
FROM '+quotename(@DB_Source)+'.'+quotename(@Table_Schema)+'.'+quotename(@Table_Name)+' x WITH (NOLOCK)
where '+quotename(@Column_Name)+'=1
' 

EXEC sp_executesql @Query, N'@K INT OUTPUT', @K=@K OUTPUT;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM