sql server showing invaild object name thouh having table - sql

Getting invalid object name <table_name> while selecting the table name, since it is connecting
select * from user.tablename giving output
select * from tablename not giving output
since connectd database as well
use dbname
please help me out here
is this any grant related issue, im using sql serevr express edition

give dbo permissions to replace the user.table_name
ALTER SCHEMA dbo transfer USER.TABLE_NAME
AND to get all this ,run below query
SELECT 'ALTER SCHEMA dbo TRANSFER ' + s.Name + '.' + o.Name
FROM sys.Objects o
INNER JOIN sys.Schemas s on o.schema_id = s.schema_id
WHERE s.Name = 'compmsauser'
And (o.Type = 'U' Or o.Type = 'P' Or o.Type = 'V')

Related

Find references to one database's columns in all other databases

I want these 5 columns as output when a stored procedure, in any database on the server, references a column in a specific database (let's say the database is AA).
Column_name Table_Name Schema_Name Procedure_Name Database_Name
Four of the columns are really easy to get - for the current database that you're in:
SELECT
TableName = t.Name,
SchemaName = s.Name,
ColumnName = c.Name,
DatabaseName = DB_NAME()
FROM
sys.tables t
INNER JOIN
sys.schemas s ON [t].[schema_id] = [s].[schema_id]
INNER JOIN
sys.columns c ON [t].[object_id] = [c].[object_id]
What you cannot get easily is all columns across all tables in all databases. Also: determining in which procedure each column is used is also rather tricky (or next to impossible).
From marc_s answer i generate a query which gives comma separated Procedure_Name depended by that table
SELECT
TableName = t.Name,
SchemaName = s.Name,
ColumnName = c.Name,
DatabaseName = DB_NAME(),
STUFF((SELECT ',' + name
FROM sys.procedures
WHERE object_id in (SELECT distinct id from sys.sysdepends
WHERE depid = (SELECT object_id FROM sys.tables
WHERE name=t.Name)
)
FOR XML PATH('')), 1, 0, '') AS sps
FROM
sys.tables t
INNER JOIN
sys.schemas s ON [t].[schema_id] = [s].[schema_id]
INNER JOIN
sys.columns c ON [t].[object_id] = [c].[object_id]

how to create XML schema from an existing database in SQL Server 2008

Is there a way to create an XML schema from an existing database in SQL Server 2008, SQL Server Management Studio?
I have a DB with ~50 tables. I'm looking to create a "nice" diagram showing the relationship between those tables. Using another application called SQL Designer (https://code.google.com/p/wwwsqldesigner/) will give me the "nice" looking picture, but I don't know how to create the XML schema required.
I did a search across the forum (and MS) and couldn't quite find my answer. I could find tools which created a database, but I'm looking at the reverse... I need a pretty picture which shows the database in diagrammatic form. I thought if I could get my db structure into XML then SQL Designer will do the rest for me.
Thanks for your assistance.
Nick
If you only need the xml schema of tables query them with this:
select top 0 * FROM daTable FOR XML AUTO,XMLSCHEMA
If you need the table names and columns in order to create a representation of your database and how tables are connected you can use something like this:
SELECT
s.name as '#Schema'
,t.name as '#Name'
,t.object_id as '#Id'
,(
SELECT c.name as '#Name'
,c.column_id as '#Id'
,IIF(ic.object_id IS NOT NULL,1,0) as '#IsPrimaryKey'
,fkc.referenced_object_id as '#ColumnReferencesTableId'
,fkc.referenced_column_id as '#ColumnReferencesTableColumnId'
FROM sys.columns as c
LEFT OUTER JOIN sys.index_columns as ic
ON c.object_id = ic.object_id
AND c.column_id = ic.column_id
AND ic.index_id = 1
LEFT OUTER JOIN sys.foreign_key_columns as fkc
ON c.object_id = fkc.parent_object_id
AND c.column_id = fkc.parent_column_id
WHERE c.object_id = t.object_id
FOR XML PATH ('Column'),TYPE
)
FROM sys.schemas as s
INNER JOIN sys.tables as t
ON s.schema_id = t.schema_id
FOR XML PATH('Table'),ROOT('Tables')
Let your application use the ColumnReferencesTableId and ColumnReferencesTableColumnId to get table relations. You could also further join back to columns and tables which are referenced if you prefer writing their names out but I thought their Ids would suffice.
Combined with a cursor running through INFORMATION_SCHEMA or sysobjects, the following should help you:
SELECT * FROM [MyTable] FOR XML AUTO, XMLSCHEMA
I'm uncertain as to whether you can simply apply this to a whole database, or what postprocessing effort would be required to combine all the various table schemas, but it's something to work with.
Try this (a variation of this answer):
DECLARE #listStr VARCHAR(MAX)
SELECT #listStr = COALESCE(#listStr+',' ,'') + TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
EXEC('
DECLARE #schema xml
SET #schema = (SELECT TOP 0 * FROM ' +
#listStr +
' FOR XML AUTO, ELEMENTS, XMLSCHEMA(''DbSchema''))
SELECT #schema
');
Replace the line:
,**IIF**(ic.object_id IS NOT NULL,1,0) as '#IsPrimaryKey'
With this:
,CASE WHEN ic.object_id IS NOT NULL THEN 1 ELSE 0 END AS '#IsPrimaryKey'
for MS SQL server versions not allowing the IIF function.

SQL how to know the datatype for a column

I'm using MS Access and MS Sql 2008, I need get the DataType for a specific column in a single table.
Could you please post a sample of code?
Try this:
SELECT
COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'schema'
AND TABLE_NAME = 'tablename';
You can also use catalog views:
SELECT sch.name [Schema],
tbl.name [Table],
col.name [Column],
typ.name [Type]
FROM sys.columns col
JOIN sys.tables tbl ON
tbl.object_id = col.object_id
AND tbl.name = 'tableName'
JOIN sys.schemas sch ON
sch.schema_id = tbl.schema_id
AND sch.name = 'schemaName'
JOIN sys.types typ ON
typ.system_type_id = col.system_type_id
I'm assuming that you want to programmatically get schema metadata for your MS Access DB, as there are other answers for SQL Server. Unfortunately, MS Access doesn't offer an information_schema catalog of views (or any real analog) to query directly, so you might have to try one of the following:
Create a linked server in SQL Server to your Access DB, and query through that.
Use something like GetOleDbSchemaTable in your app.

To get table details

I want to get all table names and fields in that table from a particular database.
Please help me to solve this.
Try looking at the sys.objects and sys.columns tables:
SELECT * FROM SYS.OBJECTS
WHERE TYPE = 'U'
Would give you all of the tables in that database (Type U)
SELECT 'Table name : ' + so.name, ' Column Name: ' + sc.name FROM SYS.OBJECTS so
INNER JOIN sys.columns sc ON sc.OBJECT_ID = so.OBJECT_ID
WHERE TYPE = 'U'
Would give you all of the tables in that database and the column names. You could filter on these queries and do WHERE so.name = 'Your Table'
http://msdn.microsoft.com/en-us/library/ms190324.aspx
use the syntax :-sp_help your table name
like this
sp_help Payroll_Shift

SQL Server: Get table primary key using sql query [duplicate]

This question already has answers here:
How do you list the primary key of a SQL Server table?
(28 answers)
Closed 3 years ago.
I want to get a particular table's primary key using SQL query for SQL Server database.
In MySQL I am using following query to get table primary key:
SHOW KEYS FROM tablename WHERE Key_name = 'PRIMARY'
What is equivalent of above query for SQL Server ?.
If There is a query that will work for both MySQL and SQL Server then It will be an ideal case.
I also found another one for SQL Server:
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE OBJECTPROPERTY(OBJECT_ID(CONSTRAINT_SCHEMA + '.' + QUOTENAME(CONSTRAINT_NAME)), 'IsPrimaryKey') = 1
AND TABLE_NAME = 'TableName' AND TABLE_SCHEMA = 'Schema'
Found another one:
SELECT
KU.table_name as TABLENAME
,column_name as PRIMARYKEYCOLUMN
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TC
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KU
ON TC.CONSTRAINT_TYPE = 'PRIMARY KEY'
AND TC.CONSTRAINT_NAME = KU.CONSTRAINT_NAME
AND KU.table_name='YourTableName'
ORDER BY
KU.TABLE_NAME
,KU.ORDINAL_POSITION
;
I have tested this on SQL Server 2003/2005
Using SQL SERVER 2005, you can try
SELECT i.name AS IndexName,
OBJECT_NAME(ic.OBJECT_ID) AS TableName,
COL_NAME(ic.OBJECT_ID,ic.column_id) AS ColumnName
FROM sys.indexes AS i INNER JOIN
sys.index_columns AS ic ON i.OBJECT_ID = ic.OBJECT_ID
AND i.index_id = ic.index_id
WHERE i.is_primary_key = 1
Found at SQL SERVER – 2005 – Find Tables With Primary Key Constraint in Database
From memory, it's either this
SELECT * FROM sys.objects
WHERE type = 'PK'
AND object_id = OBJECT_ID ('tableName')
or this..
SELECT * FROM sys.objects
WHERE type = 'PK'
AND parent_object_id = OBJECT_ID ('tableName')
I think one of them should probably work depending on how the data is stored
but I am afraid I have no access to SQL to actually verify the same.
SELECT COLUMN_NAME FROM {DATABASENAME}.INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE TABLE_NAME LIKE '{TABLENAME}' AND CONSTRAINT_NAME LIKE 'PK%'
WHERE
{DATABASENAME} = your database from your server AND
{TABLENAME} = your table name from which you want to see the primary key.
NOTE : enter your database name and table name without brackets.
select *
from sysobjects
where xtype='pk' and
parent_obj in (select id from sysobjects where name='tablename')
this will work in sql 2005
The code I'll give you works and retrieves not only keys, but a lot of data from a table in SQL Server. Is tested in SQL Server 2k5/2k8, dunno about 2k. Enjoy!
SELECT DISTINCT
sys.tables.object_id AS TableId,
sys.columns.column_id AS ColumnId,
sys.columns.name AS ColumnName,
sys.types.name AS TypeName,
sys.columns.precision AS NumericPrecision,
sys.columns.scale AS NumericScale,
sys.columns.is_nullable AS IsNullable,
( SELECT
COUNT(column_name)
FROM
INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE
WHERE
TABLE_NAME = sys.tables.name AND
CONSTRAINT_NAME =
( SELECT
constraint_name
FROM
INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE
TABLE_NAME = sys.tables.name AND
constraint_type = 'PRIMARY KEY' AND
COLUMN_NAME = sys.columns.name
)
) AS IsPrimaryKey,
sys.columns.max_length / 2 AS CharMaxLength /*BUG*/
FROM
sys.columns, sys.types, sys.tables
WHERE
sys.tables.object_id = sys.columns.object_id AND
sys.types.system_type_id = sys.columns.system_type_id AND
sys.types.user_type_id = sys.columns.user_type_id AND
sys.tables.name = 'TABLE'
ORDER BY
IsPrimaryKey
You can use only the primary key part, but I think that the rest might become handy.
Best regards,
David
This should list all the constraints and at the end you can put your filters
/* CAST IS DONE , SO THAT OUTPUT INTEXT FILE REMAINS WITH SCREEN LIMIT*/
WITH ALL_KEYS_IN_TABLE (CONSTRAINT_NAME,CONSTRAINT_TYPE,PARENT_TABLE_NAME,PARENT_COL_NAME,PARENT_COL_NAME_DATA_TYPE,REFERENCE_TABLE_NAME,REFERENCE_COL_NAME)
AS
(
SELECT CONSTRAINT_NAME= CAST (PKnUKEY.name AS VARCHAR(30)) ,
CONSTRAINT_TYPE=CAST (PKnUKEY.type_desc AS VARCHAR(30)) ,
PARENT_TABLE_NAME=CAST (PKnUTable.name AS VARCHAR(30)) ,
PARENT_COL_NAME=CAST ( PKnUKEYCol.name AS VARCHAR(30)) ,
PARENT_COL_NAME_DATA_TYPE= oParentColDtl.DATA_TYPE,
REFERENCE_TABLE_NAME='' ,
REFERENCE_COL_NAME=''
FROM sys.key_constraints as PKnUKEY
INNER JOIN sys.tables as PKnUTable
ON PKnUTable.object_id = PKnUKEY.parent_object_id
INNER JOIN sys.index_columns as PKnUColIdx
ON PKnUColIdx.object_id = PKnUTable.object_id
AND PKnUColIdx.index_id = PKnUKEY.unique_index_id
INNER JOIN sys.columns as PKnUKEYCol
ON PKnUKEYCol.object_id = PKnUTable.object_id
AND PKnUKEYCol.column_id = PKnUColIdx.column_id
INNER JOIN INFORMATION_SCHEMA.COLUMNS oParentColDtl
ON oParentColDtl.TABLE_NAME=PKnUTable.name
AND oParentColDtl.COLUMN_NAME=PKnUKEYCol.name
UNION ALL
SELECT CONSTRAINT_NAME= CAST (oConstraint.name AS VARCHAR(30)) ,
CONSTRAINT_TYPE='FK',
PARENT_TABLE_NAME=CAST (oParent.name AS VARCHAR(30)) ,
PARENT_COL_NAME=CAST ( oParentCol.name AS VARCHAR(30)) ,
PARENT_COL_NAME_DATA_TYPE= oParentColDtl.DATA_TYPE,
REFERENCE_TABLE_NAME=CAST ( oReference.name AS VARCHAR(30)) ,
REFERENCE_COL_NAME=CAST (oReferenceCol.name AS VARCHAR(30))
FROM sys.foreign_key_columns FKC
INNER JOIN sys.sysobjects oConstraint
ON FKC.constraint_object_id=oConstraint.id
INNER JOIN sys.sysobjects oParent
ON FKC.parent_object_id=oParent.id
INNER JOIN sys.all_columns oParentCol
ON FKC.parent_object_id=oParentCol.object_id /* ID of the object to which this column belongs.*/
AND FKC.parent_column_id=oParentCol.column_id/* ID of the column. Is unique within the object.Column IDs might not be sequential.*/
INNER JOIN sys.sysobjects oReference
ON FKC.referenced_object_id=oReference.id
INNER JOIN INFORMATION_SCHEMA.COLUMNS oParentColDtl
ON oParentColDtl.TABLE_NAME=oParent.name
AND oParentColDtl.COLUMN_NAME=oParentCol.name
INNER JOIN sys.all_columns oReferenceCol
ON FKC.referenced_object_id=oReferenceCol.object_id /* ID of the object to which this column belongs.*/
AND FKC.referenced_column_id=oReferenceCol.column_id/* ID of the column. Is unique within the object.Column IDs might not be sequential.*/
)
select * from ALL_KEYS_IN_TABLE
where
PARENT_TABLE_NAME in ('YOUR_TABLE_NAME')
or REFERENCE_TABLE_NAME in ('YOUR_TABLE_NAME')
ORDER BY PARENT_TABLE_NAME,CONSTRAINT_NAME;
For reference please read thru - http://blogs.msdn.com/b/sqltips/archive/2005/09/16/469136.aspx
Keep in mind that if you want to get exact primary field you need to put TABLE_NAME and TABLE_SCHEMA into the condition.
this solution should work:
select COLUMN_NAME from information_schema.KEY_COLUMN_USAGE
where CONSTRAINT_NAME='PRIMARY' AND TABLE_NAME='TABLENAME'
AND TABLE_SCHEMA='DATABASENAME'
It is also (Transact-SQL) ... according to BOL.
-- exec sp_serveroption 'SERVER NAME', 'data access', 'true' --execute once
EXEC sp_primarykeys #table_server = N'server_name',
#table_name = N'table_name',
#table_catalog = N'db_name',
#table_schema = N'schema_name'; --frequently 'dbo'