I'm writing a query to copy databases for Dynamics NAV to make test environments. The difficulty that I'm addressing is that once the new test environment is made, I need to clear out information from some of the fields so that live data doesn't get processed by the test environment.
The way that NAV sets up the tables in the database is using the format of [Company_Name$Table_Name].[Field] and in more recent versions, it adds a numerical sequence at the end of the table name.
I'm trying to add a section to my script that will dynamically go through the tables to find all instances of the Table Name and delete the data in a specified field on that table. The table name itself is constant and the fields in each of the tables with that table name are constant.
What I've tried doing so far as a test to find the data is a nested select statement to get a list of the records across those tables. I can get the table names using:
select *
from sys.tables
where name like '%table_name%
What I don't know/understand is how to pass that information in to the subquery of:
Select [Profile]from [table_name] where [field] is not null
What I tried to do was the following to just get the data in general, but when I do it says the syntax is incorrect at the end and I'm not sure :
Select *
From(select [name]
From sys.tables
where name like '%tableName%'
)
The last thing I tried was this in an attempt to put the table name in front of the field name but that didn't work either
select (select [name]
from sys.tables
where name like '%Interface Profile').[Profile]
from (
select [name]
from sys.tables
where name like '%Interface Profile') as profiles
2条答案
按热度按时间7vux5j2d1#
Here's a little generic solution you might be able to use:
I create a little foundation table
@fields_to_clear
, which you can populate with table names as LIKE and name of fields you want to clear, and finally the value you want to set. I use NULLs, but in theory, you can also set them to 0 or whatever else. Just beware that strings might require extra quotes due to the nature of dynamic SQL.Then i create a cursor which finds matching tables in the system catalog
sys.tables
and loops fields one by one. The loop builds the dynamic SQL which sets each field to the value in thefield_value_to_set
column.You can comment the EXEC(@SQL) just to see the actual SQL being generated.
Be careful with the like-string so you don't blow away your whole database
svujldwt2#
You have to alias inline views in sql server. For example this works