Solved

Querying changing table name

Posted on 2016-08-30
10
48 Views
Last Modified: 2016-08-31
SQL 2008

I have a table that I am querying from that keeps, changing the number on the end of it.
The last 4 digits keep changing on a daily or sometimes 2 or 3 times a day

Metric2824

Query
Select number, Created
from Metric2824

I go in on a daily basis and change the numbers to the maximum number

How can I change the query so it grabs the latest 4 digit number on the Metric table?

Thanks
0
Comment
Question by:halifaxman
  • 3
  • 2
  • 2
  • +3
10 Comments
 
LVL 46

Expert Comment

by:Vitor Montalvão
ID: 41776110
You'll need a dynamic query.
DECLARE @TableName AS sysname
DECLARE @MySelect AS VARCHAR(MAX)

SET @TableName='Metric2824'

SET @MySelect = 'SELECT * FROM ' + @TableName

EXEC(@MySelect)

Open in new window

0
 
LVL 33

Expert Comment

by:ste5an
ID: 41776125
You don't change that query. The user or process, which is creating that table is responsible for updating your view.

But Vitor is right, you need under most circumstances dynamic SQL for that. This should be the last step in the data import/table creation process:

DECLARE @alterview NVARCHAR(MAX) = N'ALTER VIEW Query AS SELECT M.number, M.Created FROM ? M;';
DECLARE @tablename sysname;

SET @tablename = ( SELECT TOP 1
                            T.name
                   FROM     sys.tables T
                   WHERE    T.name LIKE 'Metric____'
                   ORDER BY T.name DESC
                 );

SET @alterview = REPLACE(@alterview, '?', @tablename);

EXECUTE (@alterview);

Open in new window

0
 
LVL 65

Expert Comment

by:Jim Horn
ID: 41776388
>I go in on a daily basis and change the numbers to the maximum number
A vastly better idea would be to keep the table name the same but add a date column that stores the date of the data.  That way no one will have to use dynamic SQL to concatenate table names with the date when consuming this table.
0
 
LVL 9

Expert Comment

by:Valliappan AN
ID: 41776575
Another option is to have virtual tables, i.e. have a common table, with a field called TableName or something like that, and let users put data in the same table, with different TableName value each time. Then you can query it easily with 'select * from commonTable where TableName = (SELECT max(TableName) from commonTable)'
0
 
LVL 69

Expert Comment

by:ScottPletcher
ID: 41776710
You can avoid dynamic SQL if you can insure that only one copy of this code can run at one time.

Create a unique synonym for that code, then dynamically alter the synonym to match the new table name, like this:

DECLARE @current_table_name nvarchar(128)

SELECT TOP (1) @current_table_name = name
FROM sys.tables
WHERE name LIKE 'Metric%'
ORDER BY CAST(SUBSTRING(name, PATINDEX('%[0-9]%', name), 128) AS int) DESC

EXEC('IF OBJECT_ID(''dbo.MySyn'') IS NOT NULL DROP SYNONYM dbo.MySyn')
EXEC('CREATE SYNONYM dbo.MySyn FOR dbo.' + @current_table_name)

--from this point on, the code process "dbo.MySyn" as the "table" name, w/o needing dynamic SQL
SELECT *
FROM dbo.MySyn
WHERE ...
0
PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

 

Author Comment

by:halifaxman
ID: 41777069
Hi

Thanks for the answers I have tried

DECLARE @current_table_name nvarchar(128)

SELECT TOP (1) @current_table_name = name
FROM sys.tables
WHERE name LIKE 'Metric%'
ORDER BY CAST(SUBSTRING(name, PATINDEX('%[0-9]%', name), 128) AS int) DESC

EXEC('IF OBJECT_ID(''dbo.MySyn'') IS NOT NULL DROP SYNONYM dbo.MySyn')
EXEC('CREATE SYNONYM dbo.MySyn FOR dbo.' + @current_table_name)

--from this point on, the code process "dbo.MySyn" as the "table" name, w/o needing dynamic SQL
SELECT *
FROM dbo.MySyn

I get the error message when running it

Conversion failed when converting the nvarchar value 'Metric' to data type int.
0
 
LVL 69

Expert Comment

by:ScottPletcher
ID: 41777175
Then you have non-numeric chars after the first numeric char.  If you always need to pick up exactly 4 digits, you can do this:

SELECT TOP (1) @current_table_name = name
FROM sys.tables
WHERE name LIKE 'Metric%'
ORDER BY CAST(SUBSTRING(name, PATINDEX('%[0-9][0-9][0-9][0-9]%', name), 4) AS smallint) DESC
0
 

Author Comment

by:halifaxman
ID: 41777522
Thanks for getting back to me

I have had a look at some of the older tables and not all have 4 digits which is causing the problem

Examples

Metric_Draft
Metric94
Metric961
0
 
LVL 33

Expert Comment

by:ste5an
ID: 41777627
Why? You said the newer have all four Digits. Then just look for These tables. Either 'Metric____' or 'Metric[0-9][0-9][0-9][0-9]', depending on your nameing scheme.
0
 
LVL 69

Accepted Solution

by:
ScottPletcher earned 500 total points
ID: 41778014
Maybe this then?:

SELECT TOP (1) @current_table_name = name
FROM sys.tables
WHERE name LIKE 'Metric%'
ORDER BY create_date DESC /*get the last-created table*/
0

Featured Post

NAS Cloud Backup Strategies

This article explains backup scenarios when using network storage. We review the so-called “3-2-1 strategy” and summarize the methods you can use to send NAS data to the cloud

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

If you have heard of RFC822 date formats, they can be quite a challenge in SQL Server. RFC822 is an Internet standard format for email message headers, including all dates within those headers. The RFC822 protocols are available in detail at:   ht…
Load balancing is the method of dividing the total amount of work performed by one computer between two or more computers. Its aim is to get more work done in the same amount of time, ensuring that all the users get served faster.
Using examples as well as descriptions, and references to Books Online, show the documentation available for date manipulation functions and by using a select few of these functions, show how date based data can be manipulated with these functions.
This videos aims to give the viewer a basic demonstration of how a user can query current session information by using the SYS_CONTEXT function

911 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now