why all columns are invalid after table rename? - sql

I renamed a table and since, in evry 'select' I get the 'Invalid object name' for all columns.
I get from my select the output I need, but why I get an error too ?
this is my simple select...
SELECT [Importance]
,[Color]
,[NotificationName]
FROM [dbo].[Alerts]

It looks like you're using SQL Server Management Studio. I suspect your query will run if you try it, it's just that the intellisense doesn't know that the table name has changed.
Try Ctrl+Shift+R to refresh the cache or alternatively Edit -> Intellisense -> Refresh Local Cache.
You need to do this every time you perform schema changes.

Run below query to confirm that your table has been renamed and has the exact column names specified in your select query:
select * from sys.all_columns where object_id = OBJECT_ID('Alerts')
Alternatively you can execute below query to confirm that the Alerts table exists
IF (EXISTS (SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'Alerts'))
BEGIN
PRINT 'Alerts exists'
END
Also make sure you are in the correct database, run below query to find out the database to which Alerts belong :
SELECT TABLE_CATALOG
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'Alerts'
Once you got the database name add USE DATABASENAME at the beginning of your query or you can use DATABASENAME.dbo.Alerts.

Related

SQL Error - Cannot find the object "TABLE" because it does not exist or you do not have permissions

I've been banging my head against the wall for a week trying to figure this out. I have a script that is run during a database upgrade. I want to alter a column, "Test1", and add a column, "Test2" to a database table and when I run the script from the installer, I receive the above error. I run the script in SQL Server Management Studio and it works fine. Any help would be appreciated. Thanks.
IF (SELECT CHARACTER_MAXIMUM_LENGTH FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'TESTTABLE' AND COLUMN_NAME = 'Test1') <> -1
BEGIN
ALTER TABLE TESTTABLE ALTER COLUMN Test1 VARCHAR(MAX)
END
IF NOT EXISTS (SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'TESTTABLE' AND COLUMN_NAME = 'Test2')
BEGIN
ALTER TABLE TESTTABLE ADD Test2 VARCHAR(MAX)
END
It turned out that we are using ODBC connections to make the connection to the database, and it was not allowing (permitting, not sure) the script to change to another database by utilizing the "Use" statement within the script. I ended up creating a second connection to the appropriate database, and it worked and made the updates to the table. Thanks!

Alter table structure to match copy table

I have 2 tables corporate and corporate_copy. Initially they were same in structure but people started added new columns into corporate and forgot do do so for corporate_copy.
Somewhere in the application there is less used functionality that copies data from corporate to corporate_copy and that kept failing without anyone noticing. Now I have to add 28 columns (ofcourse with same type and length and constraints etc....).
I know it can be done in one ALTER TABLE statement but I still feel it is lengthy task.
Do we have any luxury that will make copy table same as main table by keeping data and adding default values in newly added columns?
I am asking much but is there anything like that?
--Generate a dynamic query which contain all the missing column list and Execute it
--for eg I tried Something
BEGIN TRAN
DECLARE #SqlSelect NVARCHAR(MAX),#ColumnDeclaration VARCHAR(2000)
SELECT DISTINCT ' '+COLUMN_NAME+' '+ DATA_TYPE +' '+ISNULL(CONVERT(NVARCHAR(10), CHARACTER_MAXIMUM_LENGTH ),'')+' 'Missing_Column INTO #T FROM INFORMATION_SCHEMA.COLUMNS a
WHERE a.column_name not in (SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS b
WHERE b.table_name in ('Corporate_Copy'))
and a.table_name in ('Corporate')
SELECT #ColumnDeclaration=STUFF((
SELECT ', ' + Missing_Column
FROM #T
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(max)'), 1, 1, '')
SET #SqlSelect=' ALTER TABLE Corporate_Copy Add'+ #ColumnDeclaration + ');'
PRINT #SqlSelect
ROLLBACK TRAN
You could use schema compare, found in SQL Server data tools (free) to generate a change script automatically.
But if this is just a copy, you could just run this:
DROP TABLE Corporate_Copy;
SELECT *
INTO Corporate_Copy
FROM Corporate;
It's not clear whether you really need to preserve the data in the copy. If so, it's not really a copy is it?
From SQL-Server 2015, you can use the following query to extract all different columns between 2 tables:
select distinct a.* from INFORMATION_SCHEMA.COLUMNS a
where a.column_name not in (select column_name from INFORMATION_SCHEMA.COLUMNS b
where b.table_name in ('tbl_A'))
and a.table_name in ('tbl_B')
order by a.column_name
The output gives you enough information to create a simple script to add the columns which are missing:
For exmaple:
Alter table tbl_A ADD res.Column_Name res.Data_Type ....
generate CREATE script in SSMS (right-click on table, then "script table as...")
Delete all things that already exists. Usually they are in the begining and it's a simple
change CREATE to ALTER ... ADD
That should be possible using SELECT INTO, for example the following SQL statement creates a backup copy of corporate:
SELECT * INTO corporate_copy
FROM corporate ;

How to get the "CREATE TABLE" query?

When I right-click on my view and click on "Script View As", I get the following error:
Property TextHeader is not available for View '[dbo].[TableName]'. This
property may not exist for this object, or may not be retrievable due
to insufficient access rights. The text is encrypted.
(Microsoft.SqlServer.Smo)
I was able to use bcp to get a dump of the table and also create a format file as given here. The table has about 60 columns and I do not want to manually write the CREATE TABLE query. Is there a way to do this automatically?
I was hoping that
BULK INSERT DB.dbo.TableName
FROM 'E:\Databases\TableName'
WITH (FORMATFILE = 'E:\Databases\TableName.Fmt');
GO
would do the trick but it looks like the table itself should be present in the database before I can execute the above query. Any suggestions?
You can construct the create table statement from INFORMATION_SCHEMA.Columns. Something like:
select (column_name + ' ' + data_type +
(case when character_maximum_length is not null
then '('+character_maximum_length+')'
else ''
end) + ','
) as ColumnDef
from Information_Schema.columns
order by ordinal_position
This is probably good enough. You can make it more complicated if you have to deal with numerics, for instance, or want "is null" to be accurate.
Copy the results into a new window, add the create table statement, remove the final comma and add the final closing paren.
You can do all the last step in a more complex SQL statement, but it is easier to do manually for a one-time effort.

can not get the right number of columns SQL Server

I have imported a table to my database, and to get the number of columns and assign it to a variable I do
SELECT #HowManyColumns = COUNT(COLUMN_NAME)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE (TABLE_NAME = #table_name )
But it keeps telling that the count is 0!
If I do the same for other tables it works!
I have found that the column count of the table that is not working is more than 40 columns, Why is it not working...
The data is this
Since tables w/o columns don't exists, that can only mean that the WHERE clause is not satisfied. In other words, the table named as the value of #table_name does not exists. Since you say 'sometimes it work, and some does not' that would immediately point toward case sensitive deployments. Make sure you always use the correct name for the table, with the proper case, so your code work correctly on servers which are deployed with a case sensitive collation.
Try issuing
SELECT DISTINCT TABLE_NAME
FROM INFORMATION_SCHEMA
and check table name for case.
Try having the table name as a text string instead:
DECLARE
#table_name varchar(50),
#noOfColumns int
SET
#table_name = 'table_name'
SET
#noOfColumns =
(SELECT count(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = #table_name)
PRINT #noOfColumns
The answer you get is the number of columns in the #noOfColumns variable

Get all table names of a particular database by SQL query?

I am working on application which can deal with multiple database servers like "MySQL" and "MS SQL Server".
I want to get tables' names of a particular database using a general query which should suitable for all database types. I have tried following:
SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE='BASE TABLE'
But it is giving table names of all databases of a particular server but I want to get tables names of selected database only. How can I restrict this query to get tables of a particular database?
Probably due to the way different sql dbms deal with schemas.
Try the following
For SQL Server:
SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_CATALOG='dbName'
For MySQL:
SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_SCHEMA='dbName'
For Oracle I think the equivalent would be to use DBA_TABLES.
Stolen from here:
USE YOURDBNAME
GO
SELECT *
FROM sys.Tables
GO
The following query will select all of the Tables in the database named DBName:
USE DBName
GO
SELECT *
FROM sys.Tables
GO
Just put the DATABASE NAME in front of INFORMATION_SCHEMA.TABLES:
select table_name from YOUR_DATABASE.INFORMATION_SCHEMA.TABLES where TABLE_TYPE = 'BASE TABLE'
USE DBName;
SELECT * FROM sys.Tables;
We can deal without GO in-place of you can use semicolon ;.
In mysql, use:
SHOW TABLES;
After selecting the DB with:
USE db_name
In order if someone would like to list all tables within specific database without using the "use" keyword:
SELECT TABLE_NAME FROM databasename.INFORMATION_SCHEMA.TABLES
This works Fine
SELECT
*
FROM
information_schema.tables;
I did not see this answer but hey this is what I do :
SELECT name FROM databaseName.sys.Tables;
To select the database query below :
use DatabaseName
Now
SELECT * FROM INFORMATION_SCHEMA.TABLES
Now you can see the created tables below in console .
PFA.
For Mysql you can do simple. SHOW TABLES;
select * from sys.tables
order by schema_id --comments: order by 'schema_id' to get the 'tables' in 'object explorer order'
go
In our Oracle DB (PL/SQL) below code working to get the list of all exists tables in our DB.
select * from tab;
and
select table_name from tabs;
both are working. let's try and find yours.
SELECT TABLE_NAME
FROM your_database_name.INFORMATION_SCHEMA.TABLES
ORDER BY TABLE_NAME;
Exec sp_MSforeachtable 'Select ''?'''
USE dbName;
SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE (TABLE_SCHEMA = 'dbName' OR TABLE_SCHEMA = 'schemaName')
ORDER BY TABLE_NAME
If you are working with multiple schemata on an MS SQL server, then SELECT-ing TABLE_NAME without also simultaneously selecting TABLE_SCHEMA might be of limited benefit, so I have assumed we are interested in the tables belonging to a known schema when using MS SQL Server.
I have tested the query above with SQL Server Management Studio using an SQL Server database of mine and with MySQL Workbench using a MySQL database, and in both cases it gives the table names.
The query bodges Michael Baylon's two different queries into one that can then run on either database type. The first part of the WHERE clause works on MySQL databases and the second part (after the OR) works on MS SQL Server databases. It is ugly and logically a little incorrect as it supposes that there is no undesired schema with the same name as the database. This might help someone who is looking for one single query that can run on either database server.
UPDATE FOR THE LATEST VERSION OF MSSQL SERVER (17.7)
SELECT name FROM sys.Tables WHERE type_desc = 'USER_TABLE'
Or SELECT * for get all columns.
Yes oracle is :
select * from user_tables
That is if you only want objects owned by the logged in user/schema otherwise you can use all_tables or dba_tables which includes system tables.
Building from Michael Baylon's answer, I needed a list which also included schema information and this is how I modified his query.
SELECT TABLE_SCHEMA + '.' + TABLE_NAME as 'Schema.Table'
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_CATALOG = 'dbName'
ORDER BY TABLE_SCHEMA, TABLE_NAME
Simply get all improtanat information with this below SQL in Mysql
SELECT t.TABLE_NAME , t.ENGINE , t.TABLE_ROWS ,t.AVG_ROW_LENGTH,
t.INDEX_LENGTH FROM
INFORMATION_SCHEMA.TABLES as t where t.TABLE_SCHEMA = 'YOURTABLENAMEHERE'
order by t.TABLE_NAME ASC limit 10000;
SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
ORDER BY TABLE_NAME
for postgres it will be:
SELECT table_name
FROM INFORMATION_SCHEMA.TABLES
WHERE table_schema = 'your_schema' -- probably public