Why can't I query individual columns in a SQL view? - sql

I've used a script to create a view that has the table name for every table in a database, along with the number of rows of data in the respective table. Everything works fine with SELECT *. However, I'd like to query only certain rows, but I can't seem to do that.
The view was created with the following script (credit to DatabaseZone.com for the script):
CREATE VIEW RowCount_AllTables
AS
SELECT DISTINCT
sys.schemas.name, sys.tables.name AS tableName,
sys.dm_db_partition_stats.row_count AS 'RowCount'
FROM
sys.tables
INNER JOIN
sys.dm_db_partition_stats ON sys.tables.object_id = sys.dm_db_partition_stats.object_id
INNER JOIN
sys.schemas ON sys.tables.schema_id = sys.schemas.schema_id
WHERE
(sys.tables.is_ms_shipped = 0)
When I run Select * against the resulting view, I get results such as:
name tableName RowCount
dbo Table1 2
dbo Table2 1230
dbo Table3 0
If I query just the tableName column, that works fine and returns the table names. However, if I try to query the RowCount column as well, I get the error message Incorrect syntax near the keyword 'RowCount. This happens regardless of whether I qualify the database -- it seems to not recognize RowCount as a valid column that I can call in a query. So this script fails:
SELECT RowCount
FROM RowCount_AllTables;
But this one works:
SELECT tableName
FROM RowCount_AllTables;
What's going on? I'd like to be able to alias the column names in the view in my query but I can't do that so long as I can't reference the RowCount column.
(FYI running this in SQL Server 2014)

Rowcount is a reserved word, you can select reserved words using [] as:
[Rowcount]

Thanks to #sgeddes for pointing the way. Dropped the view, changed the script for creating it to use another name for the row count column, and it now works as expected. The issue was a conflict with Rowcount being a reserved word.
Changed the create table script on this line:
SELECT distinct sys.schemas.name, sys.tables.name AS tableName,
sys.dm_db_partition_stats.row_count AS 'RowCount'
to:
SELECT distinct sys.schemas.name, sys.tables.name AS tableName,
sys.dm_db_partition_stats.row_count AS 'Row_Count'
...at which point I can now reference the Row_Count column as desired.

Related

Openquery statement in SQL Server

I am fairly new to SQL, and I am hoping someone can help me with a problem I'm having. I haven't been able to find any answers helping me figure out this exact problem.
I have two tables in two SQL Server databases on two different servers that I want to compare using the column ItemID. I want to find records from Table1 that have an ItemID that does not exist in Table2 and insert those into a table variable. I have the following code:
--Create table variable to hold query results
DECLARE #ItemIDTable TABLE
(
[itemid][NVARCHAR](20) NULL
);
--Query data and insert results into table variable
INSERT INTO #ItemIDTable
([itemid])
SELECT a.[itemid]
FROM database1.dbo.table1 a
WHERE NOT EXISTS (SELECT 1
FROM [Database2].[dbo].[table2]
WHERE a.itemid = [Database2].[dbo].[table2].[itemid])
ORDER BY itemid
This works on a test server where the two databases are on the same server, but not in real life where they are on different servers. I tried the following using OPENQUERY, but I know I haven't got it quite right.
--Create table variable to hold query results
DECLARE #ItemIDTable TABLE
(
[ItemID][nvarchar](20) NULL
);
--Query data and insert results into table variable
INSERT INTO #ItemIDTable
([ItemID])
SELECT a.[ItemID]
FROM Database1.dbo.Table1 a
WHERE NOT EXISTS (SELECT 1
FROM OPENQUERY([Server2], SELECT * FROM [Database2].[dbo].[Table2]')
WHERE a.ItemID = [Database2].[dbo].[Table2].[ItemID])
ORDER BY ItemID
I'm pretty sure I need to do something in the WHERE clause, where I have the two databases on two servers, I'm just not quite sure how to structure it. Could anyone help?
You can't create an OPENQUERY that is correlated to an outer query. You could populate a temp table with the results of an OPENQUERY and do your WHERE NOT EXISTS against the temp table, or you might want to look into Synonyms.
Openquery works like this:
select *
from openquery
(LINKED_SERVER_NAME,
'select query goes here'
)
Note that the sql portion is single quoted. That means you might have to quote the quotes if necessary. For example:
select *
from openquery
(LINKED_SERVER_NAME,
'
select SomeTextField
from SomeTable
where SomeDateField = ''20141014''
'
)

How can I Retrieve a List of All Table Names from a SQL Server CE database?

Is there some SQL that will either return a list of table names or (to cut to the chase) that would return a boolean as to whether a tablename with a certain pattern exists?
Specifically, I need to know if there is a table in the database named INV[Bla] such as INVclay, INVcherri, INVkelvin, INVmorgan, INVgrandFunk, INVgobbledygook, INV2468WhoDoWeAppreciate, etc. (the INV part is what I'm looking for; the remainder of the table name could be almost anything).
IOW, can "wildcards" be used in a SQL statement, such as:
SELECT * tables
FROM database
WHERE tableName = 'INV*'
or how would this be accomplished?
This should get you there:
SELECT *
FROM INFORMATION_SCHEMA.TABLES
where table_name LIKE '%INV%'
EDIT:
fixed table_name
To check for exists:
--
-- note that the sql compiler knows that it just needs to check for existence, so this is a case where "select *" is just fine
if exists
(select *
from [sys].[tables]
where upper([name]) like N'INV%')
select N'do something appropriate because there is a table based on this pattern';
You can try the following:
SELECT name FROM sys.tables where name LIKE 'INV%';

Get columns of index on DB2

How can I get the columns, which an index of a table uses, in DB2?
I tried:
DESCRIBE INDEXES FOR TABLE 'MYTABLE' SHOW DETAIL;
But I get the error message
ILLEGAL SYMBOL "INDEXES". SOME SYMBOLS THAT MIGHT BE LEGAL ARE: PROCEDURE PROC. SQLCODE=-104, SQLSTATE=42601, DRIVER=4.16.53
Ideally I want information of all indexes a table uses with their corresponding columns.
I am using DB2 for z/OS V9.1
You can use this query to show the indexes and their columns of your tables:
SELECT IX.tbname,
KEY.ixname,
KEY.colname
FROM sysibm.syskeys KEY
JOIN sysibm.sysindexes IX
ON KEY.ixname = IX.name
WHERE IX.tbname IN ( 'SOMETABLE', 'ANOTHERTABLE' )
ORDER BY IX.tbname,
KEY.ixname,
KEY.colname;
SELECT * FROM SYSIBM.SYSKEYS WHERE IXNAME IN
(SELECT NAME FROM SYSIBM.SYSINDEXES WHERE TBNAME = 'your_table_name')
I have tested it, it is giving us all the columns which are used in indexes.
You can use below query also. it works fine if syskeys table is missing
SELECT * FROM SYSIBM.SYSINDEXCOLUSE where INDNAME IN (SELECT NAME FROM SYSIBM.SYSINDEXES si where si.TBNAME ='your_table_Name' ) ORDER BY INDNAME, COLSEQ
I had an issue with using "KEY" as a table alias. Also, if you have multiple schemas with the same table name, use the following:
SELECT IX.TABLE_SCHEMA, IX.TABLE_NAME, IX.INDEX_NAME, KY.ORDINAL_POSITION, KY.COLUMN_NAME
FROM SYSKEYS KY
JOIN SYSINDEXES IX ON (KY.INDEX_NAME = IX.INDEX_NAME AND KY.INDEX_SCHEMA = IX.INDEX_SCHEMA)
WHERE IX.TBNAME = 'table-name' AND IX.TABLE_SCHEMA = 'table-schema'
ORDER BY IX.TABLE_SCHEMA, IX.TABLE_NAME, IX.INDEX_NAME, KY.ORDINAL_POSITION
FOR READ ONLY WITH UR

sql select into subquery

I'm doing a data conversion between systems and have prepared a select statement that identifies the necessary rows to pull from table1 and joins to table2 to display a pair of supporting columns. This select statement also places blank columns into the result in order to format the result for the upload to the destination system.
Beyond this query, I will also need to update some column values which I'd like to do in a separate statement operation in a new table. Therefore, I'm interested in running the above select statement as a subquery inside a SELECT INTO that will essentially plop the results into a staging table.
SELECT
dbo_tblPatCountryApplication.AppId, '',
dbo_tblPatCountryApplication.InvId,
'Add', dbo_tblpatinvention.disclosurestatus, ...
FROM
dbo_tblPatInvention
INNER JOIN
dbo_tblPatCountryApplication ON dbo_tblPatInvention.InvId = dbo_tblPatCountryApplication.InvId
ORDER BY
dbo_tblpatcountryapplication.invid;
I'd like to execute the above statement so that the results are dumped into a new table. Can anyone please advise how to embed the statement into a subquery that will play nicely with a SELECT INTO?
You can simply add an INTO clause to your existing query to create a new table filled with the results of the query:
SELECT ...
INTO MyNewStagingTable -- Creates a new table with the results of this query
FROM MyOtherTable
JOIN ...
However, you will have to make sure each column has a name, as in:
SELECT dbo_tblPatCountryApplication.AppId, -- Cool, already has a name
'' AS Column2, -- Given a name to create that new table with select...into
...
INTO MyNewStagingTable
FROM dbo_tblPatInvention INNER JOIN ...
Also, you might like to use aliases for your tables, too, to make code a little more readable;
SELECT a.AppId,
'' AS Column2,
...
INTO MyNewStagingTable
FROM dbo_tblPatInvention AS i
INNER JOIN dbo_tblPatCountryApplication AS a ON i.InvId = a.InvId
ORDER BY a.InvId
One last note is that it looks odd to have named your tables dbo_tblXXX as dbo is normally the schema name and is separated from the table name with dot notation, e.g. dbo.tblXXX. I'm assuming that you already have a fully working select query before adding the into clause. Some also consider using Hungarian notation in your database (tblName) to be a type of anti-pattern to avoid.
If the staging table doesn't exist and you want to create it on insert then try the following:
SELECT dbo_tblPatCountryApplication.AppId,'', dbo_tblPatCountryApplication.InvId,
'Add', dbo_tblpatinvention.disclosurestatus .......
INTO StagingTable
FROM dbo_tblPatInvention
INNER JOIN dbo_tblPatCountryApplication
ON dbo_tblPatInvention.InvId = dbo_tblPatCountryApplication.InvId;
If you want to insert them in a specific order then use try using a sub-query in the from clause:
SELECT *
INTO StagingTable
FROM
(
SELECT dbo_tblPatCountryApplication.AppId, '', dbo_tblPatCountryApplication.InvId,
'Add', dbo_tblpatinvention.disclosurestatus .......
FROM dbo_tblPatInvention
INNER JOIN dbo_tblPatCountryApplication ON
dbo_tblPatInvention.InvId = dbo_tblPatCountryApplication.InvId
order by dbo_tblpatcountryapplication.invid
) a;
Try
INSERT INTO stagingtable (AppId, ...)
SELECT ... --your select goes here

Selecting a sequence NEXTVAL for multiple rows

I am building a SQL Server job to pull data from SQL Server into an Oracle database through a linked server. The table I need to populate has a sequence for the name ID, which is my primary key. I'm having trouble figuring out a way to do this simply, without some lengthy code. Here's what I have so far for the SELECT portion (some actual names obfuscated):
SELECT (SELECT NEXTVAL FROM OPENQUERY(MYSERVER,
'SELECT ORCL.NAME_SEQNO.NEXTVAL FROM DUAL')),
psn.BirthDate, psn.FirstName,
psn.MiddleName, psn.LastName, c.REGION_CODE
FROM Person psn
LEFT JOIN MYSERVER..ORCL.COUNTRY c ON c.COUNTRY_CODE = psn.Country
MYSERVER is the linked Oracle server, ORCL is obviously the schema. Person is a local table on the SQL Server database where the query is being executed.
When I run this query, I get the same exact value for all records for the NEXTVAL. What I need is for it to generate a new value for each returned record.
I found this similar question, with its answers, but am unsure how to apply it to my case (if even possible): Query several NEXTVAL from sequence in one statement
put it in a SQL scalar function. Example:
CREATE function [dbo].SEQ_PERSON()
returns bigint as
begin
return
( select NEXTVAL
from openquery(oraLinkedServer, 'select SEQ_PERSON.NEXTVAL FROM DUAL')
)
end
I ended up having to iterate through all the records and set the ID value individually. Messy and slow, but it seems to be the only option in this scenario.
Very easy Just Use a CURSOR to Iterate with the code :
SELECT NEXTVAL AS SQ from OPENQUERY(MYSERVER, 'SELECT AC2012.NAME_SEQNO.NEXTVAL FROM DUAL')
So you can embed this select statement in any Sql statement, and Iterate by the CURSOR.
PS:
DECLARE SQCURS CURSOR
FOR SELECT (SELECT NEXTVAL AS SQ FROM OPENQUERY(MYSERVER,
'SELECT ORCL.NAME_SEQNO.NEXTVAL FROM DUAL')),
psn.BirthDate, psn.FirstName, psn.MiddleName, psn.LastName, c.REGION_CODE
FROM Person psn
LEFT JOIN MYSERVER..ORCL.COUNTRY c ON c.COUNTRY_CODE = psn.Country
OPEN SQCURS
FETCH NEXT FROM SQCURS ;
I hope that help