Find the column names of Temp table - sql

I need to find the column names of temp table.
If it is a physical table then we can either use sys.columns or Information_schema.columns system views to find the column names.
Similarly is there a way to find the column names present in temp table?

SELECT *
FROM tempdb.sys.columns
WHERE object_id = Object_id('tempdb..#sometemptable');

To get only columns name you can use this query below:
SELECT *
FROM tempdb.sys.columns
WHERE [object_id] = OBJECT_ID(N'tempdb..#temp');
To get columns name with data type you can use this query but you need to make sure sp_help runs in the same database where the table is located (tempdb).
EXEC tempdb.dbo.sp_help #objname = N'#temp';
you can achieve same result by joining against tempdb.sys.columns like below:
SELECT [column] = c.name,
[type] = t.name, c.max_length, c.precision, c.scale, c.is_nullable
FROM tempdb.sys.columns AS c
INNER JOIN tempdb.sys.types AS t
ON c.system_type_id = t.system_type_id
AND t.system_type_id = t.user_type_id
WHERE [object_id] = OBJECT_ID(N'tempdb.dbo.#temp');

Related

Column Names from SQL Server

I am trying without success to get column names of my table in SQL Server.
I have tried the following:
SELECT * FROM [myDB].INFORMATION_SCHEMA.COLUMNS where [TABLE_NAME] = N'myTable'
SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='myTable'
SELECT COLUMN_NAME , *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'myTable' AND TABLE_SCHEMA='dbo'
SELECT [name] AS [Column Name]
FROM syscolumns
WHERE id = (SELECT id FROM sysobjects WHERE [Name] = 'myTable')
SELECT c.name FROM sys.columns c
INNER JOIN sys.tables t
ON t.object_id = c.object_id
AND t.name = 'myTable'
What is being returned is, what I think is, meta data of the table.
While in fact the actual column names are:
How can I return the column names from 'myTable'?
This solution returned the list I was looking for
SELECT name
FROM sys.columns
WHERE object_id = Object_id('myTable')

Is there a group by * except [col name] in sql

I have a very fat table with more than 100 columns. I want to count the number of value of one column. But in order to do that I have to group by all the other columns (which is a pain). Is there a way to group the table by all the columns except for that one?
It works like:
select * [except col],count(col)
from table
group by * [except col];
The table is like:
(Col1,Col2,Col3,Col4,Col5,Col6,Col7,Col8,Col9.....,Col100)
(1,1,2,2,3,4,5,6......,X)
(1,1,2,2,3,4,5,6......,Y)
(1,0,2,2,3,4,5,6......,X)
(1,0,2,2,3,4,5,6......,X)
(1,0,2,2,3,4,5,6......,Y)
(1,0,2,2,3,4,5,6......,Z)
result should be
(1,1,2,2,3,4,5,6......,2)
(1,0,2,2,3,4,5,6......,4)
Agree with Gordon, if you still want to try the traditional way and don't want to mention 100 columns.
Try this:
declare #Colsql Nvarchar(Max)
Select #ColSql = isnull(#ColSql + ',','') + '['+c.name+']'
from sys.tables t inner join sys.columns c
on t.object_id = c.object_id
inner join sys.schemas sc
on t.schema_id = sc.schema_id
Where t.name = #TableName and sc.name = #SchemaName
and c.name <> #ColumnToExclude
Exec('Select ' +#ColSql+ 'Count(#ColumnToExclude) From #TableName Group By '+#ColSql)

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]

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

Query to find out the stored procedure depending on a column

I have to change the name and the datatype of a column of a table. I have about 150 stored procedures in the database, out of which about 25 refer to the same column. I need a query that can find the name of all the stored procedures which are dependent on this column.
I use this query:
SELECT OBJECT_NAME(M.object_id), M.*
FROM sys.sql_modules M
JOIN sys.procedures P
ON M.object_id = P.object_id
WHERE M.definition LIKE '%blah%'
Obviously you'd have to substitute "blah" for the name of your column.
Try this 1
From Sp
SELECT Name as [Stored Procedure Name]
FROM sys.procedures
WHERE OBJECT_DEFINITION(OBJECT_ID) LIKE '%getdate%' order by Name
From Table
SELECT t.name AS table_name,
SCHEMA_NAME(schema_id) AS schema_name,
c.name AS column_name
FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
WHERE c.name LIKE '%EmployeeID%'
ORDER BY schema_name, table_name;
Problem:
As you know there is no way to query what fields are referenced by a function or stored procedure.
The closest we can get is an approximation.
We can tell which tables are referenced and what fields might possibly be referenced by those tables.
For example, if you have "CreatedDate" referenced by the "Person" table and you join to the "Order" table (which also has a "CreatedDate" field), it will find a “false-positive” match to "Order.CreatedDate" when you were only looking for "Person.CreatedDate".
Searching the Text of the object's script for field names is unfortunately the best we can do for now.
The good news is, it won’t miss identifying fields that are actually used.
If anything it might pull in more than what were used (due to shared field names or commented out code).
The only exception would be dynamic SQL, as Tables are not linked to Object Scripts if they are embedded in a dynamic string.
Workaround:
CREATE FUNCTION [dbo].[ft_Schema_Column_Script]
(
#ScriptName nVarChar(128) = '%',
#TableName nVarChar(128) = '%',
#ColumnName nVarChar(128) = '%'
)
RETURNS TABLE
AS
RETURN
(
SELECT ##SERVERNAME[ServerName], DB_NAME()[DatabaseName],
SS.name[ScriptSchemaName], SO.name[ScriptName],
SO.type_desc[ScriptType],
TS.name[TableSchemaName], T.name[TableName], C.name[ColumnName],
UT.name[ColumnType], C.max_length[MaxLength],
C.precision[NumericPrecision], C.scale[Scale],
C.is_nullable[Nullable],
C.is_identity[IsIdentity],
C.column_id[Ordinal],
EP.value[Description]
FROM sys.sql_modules as M
JOIN sys.objects as SO--Script Object.
ON M.object_id = SO.object_id
JOIN sys.schemas as SS--Script Schema.
ON SS.schema_id = SO.schema_id
JOIN sys.sql_expression_dependencies D
ON D.referencing_id = SO.object_id
JOIN sys.tables as T
ON T.object_id = D.referenced_id
JOIN sys.schemas as TS--Table Schema.
ON TS.schema_id = T.schema_id
JOIN sys.columns as C
ON C.object_id = T.object_id
LEFT JOIN sys.types AS UT--Left Join because of user-defined/newer types.
ON UT.user_type_id = C.user_type_id
LEFT JOIN sys.extended_properties AS EP
ON EP.major_id = C.object_id
AND EP.minor_id = C.column_id
AND EP.name = 'MS_Description'
WHERE T.name LIKE #TableName ESCAPE '\'
AND C.name LIKE #ColumnName ESCAPE '\'
AND SO.name LIKE #ScriptName ESCAPE '\'
--Use RegEx to exclude false-posotives by from similar ColumnNames.
-- (e.g. Ignore the "ModifiedBy" field when matching on "Modified").
-- Use C.name instead of #ColumnName to further reduce false-positives.
AND M.definition LIKE ( N'%[ ~`!##$\%\^&*()+-=\[\]\\{}|;'''':",./<>?]'
+ C.name
+ N'[ ~`!##$\%\^&*()+-=\[\]\\{}|;'''':",./<>?]%'
) ESCAPE '\'
)
GO
Test:
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
SELECT * FROM dbo.ft_Schema_Column_Script('ScriptName', DEFAULT, DEFAULT) as C
SELECT * FROM dbo.ft_Schema_Column_Script(DEFAULT, 'TableName', DEFAULT) as C
SELECT * FROM dbo.ft_Schema_Column_Script(DEFAULT, DEFAULT, 'ColumnName') as C
SET TRANSACTION ISOLATION LEVEL READ COMMITTED
Test the example above to see if it's good enough to meet your needs.
Results:
Example output when running this function searching for the Column Name "Created".
It searches Stored Procedures (Sprocs), User-Defined-Functions (UDF's), Triggers, but not Jobs.
The cool thing is:
This not only searches for Columns referenced by Scripts,but also Scripts referenced by Columns (or Tables)!
-- Search in All Objects
SELECT OBJECT_NAME(OBJECT_ID),
definition
FROM sys.sql_modules
WHERE definition LIKE '%' + 'BusinessEntityID' + '%'
Search in Stored Procedures Only:
SELECT DISTINCT OBJECT_NAME(OBJECT_ID),
object_definition(OBJECT_ID)
FROM sys.Procedures
WHERE object_definition(OBJECT_ID) LIKE '%' + 'BusinessEntityID' + '%'