Showing posts with label SQL Server Management Studio. Show all posts
Showing posts with label SQL Server Management Studio. Show all posts

Tuesday, 14 July 2020

Mini Post: Listing ALL Databases On A Server

Heyyyy everyone, Geon still here. I hope everyone has been well during these times and keeping safe. Remember to wash your hands and wear your mask!

Now, I realized I made a few listing queries over the years: how to list all stored procedures, how to list all tables with a given name, how to list all connections... but I just realized I never did the simplest of them all:

How to list all databases on a server.

To do this, we can query the sys.databases system table. This table can provide us with a wealth of database knowledge such as:

  • Database Name
  • Database ID
  • Creation Date
  • State
  • Collation


You can filter on any of these fields as you would a regular query.

Please see below for a simple example query I've had to use recently:

SELECT 
s.name as DatabaseName,
s.database_id as DatabaseID,
s.create_date as CreationDate,
s.collation_name as Collation,
s.recovery_model as RecoveryModel,
s.state_desc
FROM 
sys.databases s
WHERE
create_date >= '01/01/2020'
ORDER BY name;

I hope this was useful to someone. :-)


DISCLAIMER: As stated, I’m not an expert so please, PLEASE feel free to politely correct or comment as you see fit. Your feedback is always welcomed. :-)


Saturday, 31 August 2019

The File "...\TestDB.mdf" Is Compressed But Does Not Reside In A Read-Only Database Or Filegroup

Hey everyone, welcome back to SQL Something!

Today we are looking at an old error that I've been meaning to post:

The file "...\TestDB.mdf" is compressed but does not reside in a read-only database or filegroup. The file must be decompressed.


This error popped up when I attempted to bring a DB online via the following command:

USE [master]
GO
ALTER DATABASE TestDB SET ONLINE
GO

 As the error message indicates, there seems to be some kinda file compression going on somewhere. This compression could either be on the folders where the MDF and LDF files for the database reside or, the compression could be on the files themselves.

Thankfully, checking the folders and files for compression and then turning compression off, is the same.

  • Right-click the folder containing the MDF/LDF files or right-click the files themselves.
  • Choose 'Properties'. (Fig. 1)
  • Choose 'Advanced...'.
  • Uncheck "Compress contents to save disk space".
  • Click 'Ok'.
  • Click 'Apply' and 'Ok'.

Fig. 1: Smash that Advanced button


Fig. 2: Remove the compression



Repeat the above for any folders or files related to the database. Note: If a folder is compressed, the folder name will be in blue font. If a file is compressed, the file icon will be slightly different.

Hopefully that should end your woes. :-)



DISCLAIMER: As stated, I’m not an expert so please, PLEASE feel free to politely correct or comment as you see fit. Your feedback is always welcomed. :-)

Tuesday, 28 May 2019

Dropping Multiple Tables That Include A Specific String In Their Names

Good day everyone!

It is I, Geon Bell, back with another SQL Something! (Still alive!)

Today we are going to look at something questionably dangerous: Dropping Multiple Tables at Once Via One Query!


Yeah, I'm shocked at myself for even suggesting that.

Not gonna lie, I still get very... anxious when performing table drops, much less doing them en masse, but it'll be fiiiine. Maybe.

On a serious note, my scenario was as follows: I had come across a situation where I restored a Azure SQL bacpac on my local machine, in order to fiddle around with it safely. The database, however, was part of an Azure DataSync and came with a bunch of tables I didn't need. Thankfully they all ended with the same suffix.

I didn't want to drop each table individually, so I went looking across the internet for an easier way and found this link: https://stackoverflow.com/questions/4393/drop-all-tables-whose-names-begin-with-a-certain-string

Thank you very much to Curt and Filip!

Now the query they gave was as follows:

DECLARE @cmd varchar(4000)
DECLARE cmds CURSOR FOR
SELECT 'drop table [' + Table_Name + ']'
FROM INFORMATION_SCHEMA.TABLES
WHERE Table_Name LIKE 'prefix%'

OPEN cmds
WHILE 1 = 1
BEGIN
    FETCH cmds INTO @cmd
    IF @@fetch_status != 0 BREAK
    EXEC(@cmd)
END
CLOSE cmds;
DEALLOCATE cmds

When I ran it (with my appropriate suffix), I got the error: "Cannot drop table MyTableName because it does not exist or you do not have permission." for each table.

Checking the online again, I saw that people removed the '[' brackets from their regular drop statements to solve that issue. It still didn't work, so I also added the schema name as well.

I then combined the three solutions: The original query, AND I removed the squared brackets AND added the schema name. The final working solution for me was as follows:

DECLARE @cmd varchar(4000)
DECLARE cmds CURSOR FOR
SELECT 'drop table SchemaName.' + Table_Name --Add schema name, remove brackets
FROM INFORMATION_SCHEMA.TABLES
WHERE Table_Name LIKE 'prefix%'

OPEN cmds
WHILE 1 = 1
BEGIN
    FETCH cmds INTO @cmd
    IF @@fetch_status != 0 BREAK
    EXEC(@cmd)
END
CLOSE cmds;
DEALLOCATE cmds

And that's that. :-)

DISCLAIMER: As stated, I’m not an expert so please, PLEASE feel free to politely correct or comment as you see fit. Your feedback is always welcomed. :-)

Saturday, 20 October 2018

Mini Post: Detecting Orphaned Users; sp_change_users_logins

Good day all! We are all the way in October 2018 and we are due for another SQL Something! Man is the year flying by!

Today, we are looking at detecting orphaned users. In short, these are usually users that do not have an associated SQL login.

You can detect these 'orphans' using the sp_change_users_login stored procedure with the @Action='Report' option.

Saturday, 25 August 2018

SSIS, Import and Export Wizard Issue: "Text was truncated". Using TypeGuessRows to Solve.


Hey everyone, Geon back from the dead with another SQL Something!

Today we take a peek at a very, *very* annoying and very old issue with importing data into a SQL Database. This problem occurs when using either the Import/Export Wizard or SSIS.

The issue can take a couple forms:
  • "Text was truncated or one or more characters had no match in the target code page."
  • "A truncation error occurred on the specified object of the specified component."
  • Etc.
The keywords here are 'truncated' or 'truncation'.

Now you may think "Well, obviously it's probably your column lengths in the destination, so just increase that.".

Well, what if your destination columns are maxed out? What if it wasn't the destination?

I'd believe you to be honest...

Wednesday, 25 October 2017

Mini Post: The Visual Studio Component Cache Is Out Of Date

Good day all and welcome back to SQL Something!

Quick post: "The Visual Studio component cache is out of date. Please restart Visual Studio.". Got this error when I tried to run a query on a DB in SQL Server Management Studio 2016. There is discussion on possible causes here, but that's about it.

There are a couple fixes for it.

Choose one of the following:

Solution 1: Restart Management Studio.

  • Close SQL Server Management Studio.
    • This should automatically clear temp files related to Management Studio.
    • Optional: Open Task Manager and stop all Visual Studio tasks.
  • Start SQL Server Management Studio.
  • Attempt query again.

Solution 2: Delete the Management Studio temp folder.

  • Close SQL Server Management Studio.
  • Browse to C:\Users\YourUserName\AppData\Local\Temp\
  • Browse to SSMS folder.
  • Delete folder and contents.
  • Start SQL Server Management Studio.
  • Attempt query again.

Solution 3: Lastly, you can try running the Disk Cleanup Utility.

  • Close SQL Server Management Studio.
  • Search for Disk Cleanup Utility.
  • Open Disk Cleanup Utility.
  • Select Temporary Files only.
  • Click OK, Delete files.
  • Start SQL Server Management Studio.
  • Attempt query again.


One of the above should work for you. :-)

DISCLAIMER: As stated, I’m not an expert so please, PLEASE feel free to politely correct or comment as you see fit. Your feedback is always welcomed. :-)

Thursday, 31 August 2017

Mini Post: DBCC SHRINKFILE Error: Msg 8985, Could not locate file in sys.database_files.

*Slides by*

Hey everyone, sliding in a post on the last day of the month of August. I already missed July :'-(

Anyways, today we will be looking at the following error(s) I got when attempting to shrink a database file via DBCC SHRINKFILE:

  • Msg 8985, Level 16, State 1, Line #
    Could not locate file 'FileName_1' for database 'DatabaseName' in sys.database_files. The file either does not exist, or was dropped.

  • Msg 5041, Level 16, State 1, Line #
    MODIFY FILE failed. File 'FileName_1' does not exist.

These errors have to do with incorrect filenames you might be using for the DBCC SHRINKFILE parameters. And by incorrect, I mean it is possible that you, like me, were not using the logical filename.

One way to double check the logical filename would be to run the following on the database in question to get the info from sys.database_files:

SELECT 
   file_id AS FileID,
   name AS LogicalFileName
   size/128.0 AS FileSizeMB,
   size/128.0 - CAST(FILEPROPERTY(name, 'SpaceUsed') AS int)/128.0
                   AS EmptySpaceMB
FROM 
   sys.database_files;

The query gives you some additional information such as file_id (which you can use instead of the logical name) as well as file size and 'empty' space to better determine your file reduction planning.

Hope this helps. :-)

DISCLAIMER: As stated, I’m not an expert so please, PLEASE feel free to politely correct or comment as you see fit. Your feedback is always welcomed. :-)

Friday, 23 June 2017

Mini Post: Find All Tables That Have A Given Column

Hey everyone! Welcome back to SQL Something!

Really quick post today. Today we look at finding a table(s) that a column belongs to. Had to find a solution to do this recently and thought it would helpful to share.

The answers we seek can be found in the following SQL Server system views:

We will retrieve the related column names from sys.columns and the table names from sys.tables.

Putting it together we get the following:

SELECT       c.name AS ColumnName, t.name AS TableName
FROM          sys.columns c
                     JOIN sys.tables t
                     ON c.object_id = t.object_id
WHERE       c.name LIKE '%YourColumn%'
ORDER BY ColumnName, TableName;

The above will list all tables that have a column name like the given column name ('YourColumn').

And there we go. :-)

DISCLAIMER: As stated, I’m not an expert so please, PLEASE feel free to politely correct or comment as you see fit. Your feedback is always welcomed. :-)

Original Reference:  https://stackoverflow.com/questions/26293085/find-all-table-names-with-column-name

Wednesday, 10 May 2017

Syncing Logins/Users Across SQL Server Instances (For Availability Groups and Mirroring Failovers)

Hey Everyone! Guess who's still around!

Welcome back to SQL Something (with a post dedicated to my friend Greg who guilt-ed me into finally starting back posts). In all seriousness, it's really been far too long.

Today's post briefly touches on SQL Server Always On Availability Groups in SQL Server 2016. You can find a pretty good tutorial on how to set up Always On Availability Groups in an Azure VM via the links here and here. They are pretty thorough (great job team Microsoft!), but they do have a couple very, very small errors/typos that I might point out in a subsequent post.

Today, however, we are merely focusing on a simple login/user issue in order to help streamline failing over to your secondary. The fix is about syncing logins between availability groups. This fix can also be applied to Mirroring (a deprecated feature after 2016)

Wednesday, 2 November 2016

Azure SQL Database Firewall Issue (Connectivity Issue)

Hey everyone! Yes, I'm still around and yes, this is still SQL Something!

I'm sounding like a broken record now but, as usual, life has been pretty busy. Definitely going to try to finish the year right however, by having at least one post for each of the last couple of months.

Now! Let's get on with it.

Today we are looking at connecting to a Azure SQL Database. In a nutshell, an Azure SQL Database is a DB that exists on a logical DB server, not an actual DB Server VM. It takes away the hassle of having to do server related admin tasks and allows you to focus on the DB itself and the data it contains.

For the purpose of this exercise, let's assume we created a Azure SQL DB and when we attempted to connect to it via Management Studio, we received the following:
Fig. 1: Danger Will Robinson!


Now, we can take the following steps:
  • Ensure that you are using the correct server name, username and password.
If the above doesn't work, we will have to verify our Azure SQL Database Firewall rules.
  • Log on to portal.azure.com with your valid user.
  • Navigate to your azure SQL Databases.
  • Click the database in question.
  • Select 'Set Server Firewall'.

Fig. 2: Firewall awesomeness.

  • Click add Client IP.

Fig. 3: Add yo IP
  • Click 'Save'.

Now we can retry our connection.

And that's all there is to it. :-)

DISCLAIMER: As stated, I’m not an expert so please, PLEASE feel free to politely correct or comment as you see fit. Your feedback is always welcomed. :-)

Monday, 22 August 2016

Mini Post: SQL Server Agent Job History

Hey all, welcome back to SQL Something. Man, has it been a while. Too long.

Unfortunate to say however, this post will not be particularly epic to make up for the long absence. Like, not epic at all. But, you know what? Let's go into it. If it helps one person, then that's plenty. :-)

Today we are looking at SQL Server Agent Job history.

A SQL Server Job allows us to automate a process to run at particular times, either as a one time event or repeatedly for some specified duration (or indefinitely). Setting up jobs for performing backups is an example of a great way to use jobs.

A job's history can show us a number of things. It can show us if the job ran successfully and if not, it can give us an indicator as to why. It can also show us some useful info such as the creds used to invoke the job, as well as the duration of time taken for the job to run (this last I find pretty helpful).

Wednesday, 27 April 2016

Viewing Collation (Server/Database/Column) Via T-SQL

Hey everyone and welcome back to SQL Something!

Real quick one today and that is viewing Collation information via T-SQL (I will do a follow up post eventually on how to do it via Management Studio with pictures).

Now onto the T-SQL.

Monday, 30 November 2015

Using The RANK() Function

Hey everyone! Welcome to (or back to) SQL Something!

Quick filler for this month: Using The RANK() Function.

I will demonstrate this function using a very simplistic example.

Firstly let's look at a table I created called [Files] that consists of the below dummy data:

Fig. 1: Important data...

Monday, 31 August 2015

Mini Post: The data types ntext and varchar are incompatible in the equal to operator.

Hello and welcome back to SQL Something!

It's Geon coming in at the eleventh hour to drop a post before the month is up.

Today we are going to look at the following error(s):

Msg 402, Level 16, State 1, Line <number>
The data types ntext and varchar are incompatible in the equal to operator.

OR

Msg 306, Level 16, State 2, Line <number>
The text, ntext, and image data types cannot be compared or sorted, except when using IS NULL or LIKE operator.

Fig. 1: #ntextProblems


As the text is basically saying, these errors occur when you try to use an equal operator ("=") to compare a varchar value to a ntext value.
So what can you use to compare? The answer is right in the second error. You can use a LIKE.


See the example below:

...WHERE ntextValue LIKE 'SomeTextValue'...

Simple enough. :-)



DISCLAIMER: As stated, I’m not an expert so please, PLEASE feel free to politely correct or comment as you see fit. Your feedback is always welcomed. :-)

Wednesday, 29 July 2015

List Multiple Row Values on Single Row (Comma Separated List)


Hey every and any body! Welcome back (or welcome to) SQL Something!

The main post for this month is looking at how to create a comma separated list for a one to many relationship (found either within the same table or between two tables).

Let's look at the following. Suppose I have the following values in a table:

Fig. 1: Transactions and their Messages...


You can see there exists a one to many relationship between this table (Table1) and another table (Table2) where multiple messages in Table1 correspond to single transaction in Table 2.

Suppose we wanted to list only the transactions and their corresponding messages. We can list the results as follows:

Fig. 2: List of Transactions and their Messages...

But suppose we want to list all the corresponding messages in one field as follows:

Single row list of Transactions and their Messages...

To achieve that we'll have to use FOR XML, specifically the FOR XML PATH variant. We can then use the below query:

--------------------------------------------------------------------------------------

SELECT T1.Tran_ID,
        (   SELECT       T2.Message + ','
            FROM          [Table1] T2
            WHERE       T2.Tran_ID = T1.Tran_ID
            ORDER BY T2.Message
            FOR XML PATH('')
        ) AS Transactions
FROM [Table1] T1
GROUP BY Tran_ID;

--------------------------------------------------------------------------------------

What this query does is reference itself with a subquery for each instance of a Tran_ID. For each instance of a Tran_ID, it looks for the corresponding messages and, using FOR XML PATH(''), it concatenates them with a comma separator.

By providing a 'blank' hierarchy in the FOR XML PATH clause, SQL does not create any element tabs and so we get one continuous string. A very good read up on the various FOR XML variations can be found here.

And that's it. :-)

DISCLAIMER: As stated, I’m not an expert so please, PLEASE feel free to politely correct or comment as you see fit. Your feedback is always welcomed. :-)

Monday, 29 June 2015

Mini Post: Using sp_executesql

Hey everyone and welcome back to SQL Something!

Today I'm going to slip in a quick post before the month ends. Today we are going to look at sp_executesql.

This system stored procedure allows users to run batches of T-SQL code. Its use of parameters allowed for a bit more security as opposed to using something like EXEC by itself. Below we can see a simple example of the format needed to use sp_executesql.

--------------------------------------------------------------------------------------

DECLARE @SQLString NVARCHAR(500); 
SET @SQLString = N'SELECT @MessageOut = f.message
                                     FROM Test.dbo.Files f 

                                     WHERE File_ID = @level';

DECLARE @ParmDefinition NVARCHAR(500);
SET @ParmDefinition = N'@level tinyint,
                                            @MessageOut varchar(30) OUTPUT'
;

DECLARE @Result VARCHAR(30);

EXEC sp_executesql
@SQLString,
@ParmDefinition,
@level = 2,
@MessageOut = @Result OUTPUT;

SELECT @Result;

-------------------------------------------------------------------------------------- 

To use sp_executesql we can to do the following:
  • Declare a SQLString variable to hold the T-SQL query/batch we would like to run.
  • Declare a Parameter Definition string to hold a string of parameters that we would like to use. We can also declare a OUTPUT parameter here in order to pass information back to the caller.
  • If you are returning information you may want to declare a variable to store the returned information (@Result).
  • Use the sp_executesql system stored procedure and give it the SQL String variable as well as the parameter definition and the values for each parameter defined. If you have an OUTPUT parameter you can save the result to your @Result variable.
  • Finally, select your @Result if you have one.

And there you go. You can help prevent SQL Injection in your applications this way. :-)

EDIT: Also, and I may go into this in more detail later, but I saw a very good demonstration illustrating that sp_executesql caches execution plans even if you use different parameter values. This can help speed up queries a good bit. :-)


DISCLAIMER: As stated, I’m not an expert so please, PLEASE feel free to politely correct or comment as you see fit. Your feedback is always welcomed. :-)

Tuesday, 19 May 2015

How to Get the Last (Latest/Newest) Record in a One-to-Many Relationship/Join

Good day everyone and welcome back to SQL Something!

Today we're looking at an issue that was presented to me today: How to get the last record in a one to many relationship.

Some digging online found this original post here, which I then had to deconstruct to understand it. To that end, I made a couple test tables and then went through the query, while making small modifications to suit my needs.

Let's go through it.

Friday, 20 March 2015

Mini Post: Saving changes is not permitted. The changes you have made require...

Hey Everyone! (Capital 'E' since you are all that important!)

Welcome to or welcome back to SQL Something!

A real quick one today to maintain my quota: Saving changes is not permitted. The changes you have made require the following tables to be dropped and re-created.

Fig. 1: Oh Noes!


You may encounter this error when you try to make adjustments to columns of a table that has data in it. Examples are dropping/adding a column(s).

Simple enough to 'fix'.


Monday, 16 February 2015

Mini Post: List All Stored Procedures/Functions In A Database (Information_Schema.Routines)

Hey all! Welcome to, or welcome back, to SQL Something!

Today we're taking a quick look at how to list all Stored Procedures (and Functions) in a database. As per usual, I needed to do this at some point for my job and so I'm sharing what I found. :-)

In order to get the information we need we will be querying information_schema.routines as follows:

SELECT    ROUTINE_NAME as 'Stored Procedure',
        ROUTINE_CATALOG as 'Database Name',
        ROUTINE_SCHEMA as 'Database Schema',
        ROUTINE_TYPE as 'Object Type (PROCEDURE/FUNCTION)',
        ROUTINE_DEFINITION as 'Stored Procedure Definition',
        CREATED as 'Date Created',
        LAST_ALTERED as 'Date Last Altered'
FROM information_schema.routines with (nolock)
WHERE ROUTINE_TYPE = 'PROCEDURE'
ORDER BY ROUTINE_NAME

The above will list all Store Procedures for the database that you run the query on. Very helpful! :-)


Now you'll notice the WHERE clause specifies the PROCEDURE type only. If we wanted info on Functions as well as Stored Procedures, we can remove this clause.


If we wanted info on Functions only and wanted some additional info like what value the Function returns, we tweak the query as follows:

SELECT    ROUTINE_NAME as 'Function Name',
        ROUTINE_CATALOG as 'Database Name',
        ROUTINE_SCHEMA as 'Database Schema',
        ROUTINE_TYPE as 'Object Type (PROCEDURE/FUNCTION)',
        ROUTINE_DEFINITION as 'Function Definition',
        DATA_TYPE as 'Return Value Type',
        CREATED as 'Date Created',
        LAST_ALTERED as 'Date Last Altered'
FROM information_schema.routines with (nolock)
WHERE ROUTINE_TYPE = 'FUNCTION'
ORDER BY ROUTINE_NAME

DATA_TYPE returns the data type of the Function's return value or it returns TABLE if it's a table valued function.


DISCLAIMER: As stated, I’m not an expert so please, PLEASE feel free to politely correct or comment as you see fit. Your feedback is always welcomed. :-)

Tuesday, 8 April 2014

Mini Post: Showing Permissions Granted To A User, Via T-SQL

Hey everyone! Welcome back to SQL Something!

Today we are going to take a quick look at how to view the available permissions a user was granted. I needed this the other day when I wanted to create a user with similar permissions for another DB. Luckily fn_my_permissions has all the answers we need.

We can query fn_my_permissions to find out permissions info at a DB level like so:

USE YourDBName;
SELECT *
FROM fn_my_permissions (NULL, 'DATABASE');

This, however, will list the permissions for the current user doing the query (which might not actually be the user you want the info for).

To find permissions for a specific user, you must first impersonate that user like so:

USE YourDBName;
EXECUTE AS USER 'User1';
SELECT *
FROM fn_my_permissions (NULL, 'DATABASE');
REVERT;

Please note that using the EXECUTE command will give you only the permissions of the user you are impersonating. You need the REVERT command at the end of the query to give yourself back the permissions you previously had.

DISCLAIMER: As stated, I’m not an expert so please, PLEASE feel free to politely correct or comment as you see fit. Your feedback is always welcomed. :-)