I am trying to select Max(ID) for all tables in my database. I tried the below query but there is no AUTO-INCREMENT column available. Is there something else that I can try?
SELECT TABLE_NAME, AUTO_INCREMENT
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = 'mydb'
Are you trying to get the max value for each IDENTITY column in your DB? that is possible by modifying the script in a previous answer to examine the is_identity column on the sys.columns table.
CREATE TABLE #x(t NVARCHAR(520), c BIGINT);
DECLARE #sql NVARCHAR(MAX);
SET #sql = N'';
SELECT #sql = #sql + N'INSERT #x SELECT '''
+ QUOTENAME(s.name) + '.' + QUOTENAME(t.name) + ''',
MAX(' + c.name + ') FROM '
+ QUOTENAME(s.name) + '.' + QUOTENAME(t.name) + ';'
FROM sys.columns C
INNER JOIN sys.tables T ON C.object_id = T.object_id
INNER JOIN sys.schemas s ON S.schema_id = T.schema_id
WHERE is_identity = 1;
EXEC sp_executesql #sql;
SELECT t, c FROM #x;
DROP TABLE #x;
CREATE TABLE #x(t NVARCHAR(520), c BIGINT);
DECLARE #sql NVARCHAR(MAX);
SET #sql = N'';
SELECT #sql = #sql + N'INSERT #x SELECT '''
+ QUOTENAME(s.name) + '.' + QUOTENAME(t.name) + ''',
MAX(ID) FROM '
+ QUOTENAME(s.name) + '.' + QUOTENAME(t.name) + ';'
FROM sys.tables AS t
INNER JOIN sys.schemas AS s
ON t.[schema_id] = s.[schema_id]
INNER JOIN sys.columns AS c
ON t.[object_id] = c.[object_id]
WHERE c.name = N'ID';
EXEC sp_executesql #sql;
SELECT t, c FROM #x;
DROP TABLE #x;
Related
I have a schema where I have multiple tables some with time and some without it. So I created a query where I have listed 3 tables say which has time like this :
WITH CTE AS
(
SELECT
CONCAT(schema_name(t.schema_id), '.', t.name) AS table_name,
c.name AS 'time'
FROM
sys.tables t
INNER JOIN
sys.columns c ON c.object_id = t.object_id
WHERE
schema_name(t.schema_id) = 'Prod'
AND c.name = 'mytime'
)
SELECT * FROM CTE
Now my output looks like ( I am showing 3 rows for the example):
Table O
table_name time
--------------------------
Prod.tableA mytime
Prod.tableB mytime
Prod.tableC mytime
So usually what I want is to get the max(mytime) from each Table/Schema combination . So for a single table I can do
SELECT MAX(mytime)
FROM Prod.tableA
However in this case I want to generate this from table O for each table and my output should look like:
Table F
table_name mymax(time)
--------------------------------------------
Prod.tableA max(mytime) from Prod.tableA
Prod.tableB max(mytime) from Prod.tableA
Prod.tableC max(mytime) from Prod.tableA
How to achieve this using another select/variable declaration etc? Any help or ideas will be extremely appreciated. Thanks in anticipation.
Can this help? You still have a bit of work, check if the output is what you like and then uncomment the exec.
DECLARE #SchemaName NVARCHAR(100) = 'foo',
#ColumnName NVARCHAR(100) = 'bar',
#sql NVARCHAR(max)
SELECT #SchemaName + '.'+ t.name AS [Schema.Table],'( SELECT MAX(' + #ColumnName + ') FROM ['+ #SchemaName +'].['+t.name+']) ' AS MaxValue
FROM sys.tables t
JOIN sys.schemas s ON t.schema_id = s.schema_id
WHERE s.name = #SchemaName
-------
SELECT #sql =
STUFF((
SELECT 'UNION ALL ' + 'SELECT ' + '''' + '[' + ISNULL(#SchemaName,'') + '].['+ t.name + ']' + '''' + ' AS [Schema.Table] ,( SELECT MAX(' + #ColumnName + ') FROM ['+ #SchemaName +'].['+t.name+']) AS Max' + #ColumnName + ' '
FROM sys.tables t
JOIN sys.schemas s ON t.schema_id = s.schema_id
WHERE s.name = #SchemaName
for xml path('')
),1,10,'')
PRINT #sql
--EXEC(#sql)
I want to replace a single character in each column of every table of the database; however, I don't want to do it table-by-table.
Is there a way to do the whole thing in one attempt?
Assuming only text values will be modified, you can do something like below.
IF(NOT EXISTS (SELECT * FROM sys.tables where name = 'TEMPQUERYTABLE' and type_desc = 'USER_TABLE'))
BEGIN
SELECT T.name AS Table_Name ,
C.name AS Column_Name ,
P.name AS Data_Type ,
P.max_length AS Size ,
CAST(P.precision AS VARCHAR) + '/' + CAST(P.scale AS VARCHAR) AS Precision_Scale
INTO TEMPQUERYTABLE
FROM sys.objects AS T
JOIN sys.columns AS C ON T.object_id = C.object_id
JOIN sys.types AS P ON C.system_type_id = P.system_type_id
WHERE T.type_desc = 'USER_TABLE' AND P.name in ('nvarchar','varchar') AND T.name <> 'TEMPQUERYTABLE'
END
DECLARE #SQL NVARCHAR(MAX)
DECLARE #Old_value VARCHAR(10)
DECLARE #New_value VARCHAR(10)
SET #Old_value = 'xx'
SET #New_value = 'yy'
SET #SQL = ''
SELECT #SQL = #SQL + 'UPDATE ' + Table_Name + ' SET ' + Column_Name + ' = REPLACE(' + Column_Name + ',' + #Old_value +','+ #New_value + ')' + CHAR(13) + CHAR(10)
FROM TEMPQUERYTABLE
EXEC(#SQL)
--DROP TABLE TEMPQUERYTABLE
But I'm curious to know why you need such thing done in the first place.
I have this stored procedure and I want to revise it to be to rebuild more than one index.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [Landing].[usp_IndexDisableRebuild]
(#Schema_Name VARCHAR(256),
#Table_Name VARCHAR(256),
#Task_Name VARCHAR(256))
AS
-- Set to get the dynamic Script for
DECLARE #sql VARCHAR(MAX)
SET #sql = (SELECT 'ALTER INDEX ' + QUOTENAME(I.name) + ' ON ' + QUOTENAME(SCHEMA_NAME(T.schema_id))+'.'+ QUOTENAME(T.name) + #Task_Name FROM sys.indexes I INNER JOIN sys.tables T ON I.object_id = T.object_id INNER Join sys.schemas s ON s.schema_id = t.schema_id WHERE I.type_desc = 'NONCLUSTERED' AND I.name IS NOT NULL --AND I.is_disabled = 0 AND t.name = #Table_Name AND s.name = #Schema_Name )
-- Execute the dynamic SQL
EXEC (#sql)
I agree with the comments that you should consider using Ola Hallengren's SQL Server Maintenance Solution.
That being said, you could change your proc like to example below. In addition to correcting the subquery error, this uses the proper data types. Not sure what you want to do with #Task_Name so I just appended the value as a comment.
ALTER PROCEDURE [Landing].[usp_IndexDisableRebuild]
#Schema_Name sysname,
#Table_Name sysname,
#Task_Name VARCHAR(256)
AS
DECLARE #SQL nvarchar(MAX);
SET #SQL = (
SELECT 'ALTER INDEX ' + QUOTENAME(I.name)
+ ' ON ' + QUOTENAME(SCHEMA_NAME(T.schema_id))+'.'+ QUOTENAME(T.name) + ' REBUILD;
--' + #Task_Name + '
'
FROM sys.indexes I
INNER JOIN sys.tables T ON I.object_id = T.object_id
INNER Join sys.schemas s ON s.schema_id = t.schema_id
WHERE I.type_desc = 'NONCLUSTERED'
AND I.name IS NOT NULL
AND I.is_disabled = 0
AND t.name = #Table_Name
AND s.name = #Schema_Name
FOR XML PATH(''), TYPE).value('.','nvarchar(MAX)');
--PRINT #SQL;
EXECUTE sp_executesql #SQL;
GO
I'm working on updating all the tables on a DB and I am having trouble getting the code correct. I was given the below code but as a previous solution but I am trying to use the SP_msforeachtable and can't get the correct format. And help with this would be wonderful. Here is the code:
USE TPP_DB
GO
DECLARE #SQL NVARCHAR(MAX)
EXEC sp_MSforeachtable
'SELECT #SQL = (
SELECT ''
UPDATE ''' + QUOTENAME(SCHEMA_NAME(o.[schema_id])) + ''.'''' + QUOTENAME(o.name) + '''
SET ''' + QUOTENAME(c.name) + '' = NULL
WHERE '' + QUOTENAME(c.name) + '' = '''''
FROM sys.columns c
JOIN sys.objects o ON c.[object_id] = o.[object_id]
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)')
PRINT #SQL
EXEC sys.sp_executesql #SQL'
You can try like this,
SELECT 'UPDATE ' + Schema_name(t.schema_id) + '.'
+ t.NAME + ' SET ' + c.NAME + ' =NULL WHERE ' + c.NAME
+ ' ='''';'
FROM sys.tables AS t
INNER JOIN sys.columns c
ON t.OBJECT_ID = c.OBJECT_ID
--WHERE c.NAME = 'ModifiedDate'
ORDER BY Schema_name(t.schema_id),
t.NAME;
I have around 150 tables in my database and now I need to add a column constraint(InsertedOn) on to each and every table with a default value of GetDate()
I have tried below code to accomplish the task
exec sp_msforeachtable 'ALTER TABLE ? ADD CONSTRAINT DF_InsertedOn DEFAULT GetDate() FOR [InsertedOn]';
But my problem is constraint name,The above code fails when its trying to create the constraint for the second table since the name of the constraint in use
Is there any way to accomplish the task using the same sp_msforeachtable ?
Thank you.
Try this one -
DECLARE #SQL NVARCHAR(MAX)
SELECT #SQL = STUFF((
SELECT CHAR(13) + 'ALTER TABLE [' + s.name + '].[' + o.name + ']
ADD [InsertedOn] DATETIME NOT NULL CONSTRAINT [DF_' + o.name + '_InsertedOn] DEFAULT GETDATE()'
FROM sys.objects o WITH (NOWAIT)
JOIN sys.schemas s WITH (NOWAIT) ON o.[schema_id] = s.[schema_id]
WHERE NOT EXISTS(
SELECT 1
FROM sys.columns c WITH (NOWAIT)
WHERE c.[object_id] = o.[object_id]
AND c.name = 'InsertedOn'
)
AND o.[type] = 'U'
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
PRINT #SQL
EXEC sys.sp_executesql #SQL
Output -
ALTER TABLE [tt].[t1]
ADD [InsertedOn] DATETIME NOT NULL CONSTRAINT [DF_t1_InsertedOn] DEFAULT GETDATE()
ALTER TABLE [tt].[t2]
ADD [InsertedOn] DATETIME NOT NULL CONSTRAINT [DF_t2_InsertedOn] DEFAULT GETDATE()
To generate scrips you can use this code. It uses system views sys.tables, sys.schemas and sys.columns
DECLARE #ColumnName VARCHAR(100) = 'InsertedOn'
SELECT
'ALTER TABLE ' + s.name + '.' + t.name +
' ADD CONSTRAINT DF_' + t.name + '_' + #ColumnName +
' DEFAULT GetDate() FOR ' + #ColumnName
FROM sys.tables t
JOIN sys.schemas s ON s.schema_id = t.schema_id
WHERE EXISTS (
SELECT *
FROM sys.columns c
WHERE c.object_id = t.object_id
AND name = #ColumnName
)