SQL Server Management Studio connection defaults to 'master' when selecting a database-specific object - sql

In SQL Server 2008 R2 Management Studio, if I right-click on an object inside a specific database and choose "Select top 1000 rows ..", the database connection for the query window always opens on 'master' while the table name is fully qualified as [database].[dbo].[table]. This makes it impossible to jump in and tweak out this query and insert joins, etc., to the statement without also fully-qualifying everything I add, or add a USE statement, or select the database from the drop-down menu.
Is there a setting or something that will make query windows open with a database connection of the selected object browser's database rather than connect to 'master', and not fully qualify the object's database in the query text? I realize that I can register my SQL connection to default to my database, but we actually go through multiple new databases every week--in a given month I will have touched tens of databases--so it would be difficult to manage multiple database registrations. I would rather it if SSMS just connected to the specified database. Possible and straightforward?

If you are going in via Win Auth, are in a group, are using SA or some other userid, or are in a situation where changing your login is not really the solution, AND if all you wish to do is default to a database in the query editor:
In an existing open query editor, right-click, select Connection, Change Connection.
Click the Options button to expand the options.
In the Connection Properties tab, select the database you wish to connect to.
SSMS will remember your selection for that server. You may have to repeat for other servers, but it does remedy having a default database other than master.

There is no such setting for the SELECT TOP command, but you may be able to do this by changing the default database for your login. This is tedious if you're doing this often for various databases (much like changing the registrations, as I just noticed you already outlined).
Instead of using SELECT TOP 1000 (which in addition to not putting you in the right database context, also puts a TOP in that I assume you're just going to remove as well), you should right-click the table and choose Script Table as > SELECT to > New Query Window. This puts the context in the right DB, adds a USE command, doesn't have a TOP and doesn't database-prefix the table name.

If you want query window connects to some database by default, in SSMS go to the Security -> Logins, select the login that you use to connect to this server, and loock at the properties window. In page 'general' change the default database from 'master' to database you want to connect.

You could just put a USE [database name] at the top of the query window prior to executing a query. You do not need to fully qualify the database names if you do this. If you generate any scripts and version control them, this is a good practice to put at the top anyway. It at least prevents executing the script erroneously against the wrong database (say creation of a stored procedure).
USE MySpecialDatabase
GO
SELECT * FROM MySpecialTable

Related

Create a query that generates an insert statement in SQL Server 2016

I have two tables that I've been working with in our test environment that I need to copy into my SQL Express database so I can continue work on my interface. I would like to use the data that I already have populated in the test environment tables since I don't necessarily want to use production data. I already have the tables created on my local database, all I need to do is insert the data that I already have.
I'm wondering if it's possible to generate an insert query that would contain all of the data that is already in the test environment - something that I can just execute as a query on my local machine.
Is this possible? I can't necessarily work with live production data quite yet, as my interface will be manipulating it.
1. Connect to your TEST server on SQL Server management studio.
2. Expand the Databases node.
3. Right-click your Test Database > Tasks > Generate Scripts:
4. The Introduction page opens. Select Next to open the Chose Objects page. You can select the entire database or specific objects in the database. Select Script specific database objects (select tables table)
5. Select Next to open the Set Scripting Options page. Here you can configure where to save the script and some additional advanced options.
a. Select Save to new query window.
b. Select Advanced and make sure these options are set:
Types of data to script set to Data only.
Step 5.b
Use the SQL Server Import and Export Wizard instead:
https://learn.microsoft.com/en-us/sql/integration-services/import-export-data/start-the-sql-server-import-and-export-wizard?view=sql-server-2017

SQL Server Management Studio requiring full table path

Yesterday, in SQL Server Management Studio (SSMS) (v17.6) I could write and execute:
select * from MyTable;
Today, I now must write:
Select * from myDbName.dbo.MyTable;
However, the old syntax will recognize that the table is there and pull back the headers, but no content. Also, the intellisense with the older syntax.
Yet, in my VB code, I can still use the initial statement shown above.
Why? And, how do I change it back?
You are likely connected to another database on the instance. This commonly happens when the default database for the login isn't set to something explicitly. It defaults the the master database. You'll need to change it in the drop down for intellisense to pick up your table names, and for you to not have to fully qualify the server.database.schema.table.
Also, in the bottom right of your query window, make sure the query window which you are executing your query from is actually connected to the correct database. Since you aren't getting results back, I'd bet that you are also not connected to the correct database when you run your query, but an older or developmental database (where the data is different).

Unable to import/link table from SQL Server into access. Too many indexes error

I am trying to import a table from SQL into access but I am getting too many indexes in the table error. The table in SQL is indexed to several tables and unfortunately I don't have the rights to modify or change the table anyway. just have read access in the DB. I am trying to import/link the table but I am unable to do so due to too many indexes error being thrown.
Is it possible to only import/link the data and not indexes? I know access has a limit of 32 indexes. I have cleared auto indexes in options too, but I still get the error.
Is there a solution as to how I can import/link this table in access?
Thanks in advance
I did some digging on how to avoid this problem. So the problem is we can't directly link to the SQL database if the table has a lot of indexes and Access will throw an error "too many indexes on the table you are trying to import".
one way to beat this is by putting together a "Pass-through query". Lot of people suggested VBA code. I am not a coder and could not get it to work effectively. However, Access gives you the capability to build it with out VBA and the solution I found was in Microsoft website.
The steps are as follows: you might have to work around it for 2010 due to different naming convention when compared to 2007.
On the Create tab, click Query Design in the Other group.
Click Close in the Show Table dialog box without adding any tables or queries.
Save the query. Open the Query in design mode
On the Design tab, click Pass-Through in the Query Type workgroup.
Click Property Sheet in the Show/Hide workgroup to display the property sheet for the query.
In the query property sheet, place the mouse pointer in the ODBC Connect Str property, and then, click the Build (...) button.
With the ODBC Connect Str property, you specify information about the database to which you want to connect. You can type the connection information, or click Build, and then enter information about the server to which you are connecting.
When you are prompted to save the password in the connection string, click Yes if you want the password and logon name to be stored in the connection string information.
If the query is not the type that returns records, set the ReturnsRecords property to No.
In the SQL Pass-Through Query window, type your pass-through query. For example, the following pass-through query uses the Microsoft SQL Server TOP operator in the SELECT statement to return only the first 25 orders in the Orders table from the sample Northwind database:
SELECT TOP 25 orderid from orders
To run the query, click Run in the Results group on the Design tab. For a SQL pass-through query that returns records, click Datasheet view on the status bar.
If necessary, Microsoft Access prompts you for information about your server database.
This worked for me. If some one is having the same problem you can use these steps.

Create SQL script that create database and tables

I have a SQL database and tables that I would like to replicate in another SQL Server. I would like to create a SQL script that creates the database and tables in a single script.
I can create "Create" script using the SQL Management Studio for each case (Database and Tables), but I would like to know if combining the both "Create" scripts into single script would be enough.
Thanks.
Although Clayton's answer will get you there (eventually), in SQL2005/2008/R2/2012 you have a far easier option:
Right-click on the Database, select Tasks and then Generate Scripts, which will launch the Script Wizard. This allows you to generate a single script that can recreate the full database including table/indexes & constraints/stored procedures/functions/users/etc. There are a multitude of options that you can configure to customise the output, but most of it is self explanatory.
If you are happy with the default options, you can do the whole job in a matter of seconds.
If you want to recreate the data in the database (as a series of INSERTS) I'd also recommend SSMS Tools Pack (Free for SQL 2008 version, Paid for SQL 2012 version).
In SQL Server Management Studio you can right click on the database you want to replicate, and select "Script Database as" to have the tool create the appropriate SQL file to replicate that database on another server. You can repeat this process for each table you want to create, and then merge the files into a single SQL file. Don't forget to add a using statement after you create your Database but prior to any table creation.
In more recent versions of SQL Server you can get this in one file in SSMS.
Right click a database.
Tasks
Generate Scripts
This will launch a wizard where you can script the entire database or just portions. There does not appear to be a T-SQL way of doing this.
An excellent explanation can be found here: Generate script in SQL Server Management Studio
Courtesy Ali Issa Here's what you have to do:
Right click the database (not the table) and select tasks --> generate scripts
Next --> select the requested table/tables (from select specific database objects)
Next --> click advanced --> types of data to script = schema and data
If you want to create a script that just generates the tables (no data) you can skip the advanced part of the instructions!
Not sure why SSMS doesn’t take into account execution order but it just doesn’t. This is not an issue for small databases but what if your database has 200 objects? In that case order of execution does matter because it’s not really easy to go through all of these.
For unordered scripts generated by SSMS you can go following
a) Execute script (some objects will be inserted some wont, there will be some errors)
b) Remove all objects from the script that have been added to database
c) Go back to a) until everything is eventually executed
Alternative option is to use third party tool such as ApexSQL Script or any other tools already mentioned in this thread (SSMS toolpack, Red Gate and others).
All of these will take care of the dependencies for you and save you even more time.
Yes, you can add as many SQL statements into a single script as you wish. Just one thing to note: the order matters. You can't INSERT into a table until you CREATE it; you can't set a foreign key until the primary key is inserted.

How do I make a script in SQL Management Studio 2005?

I have a table in an MS SQL Server db. I want to create a script that will put the table and all records into another db. So I right-click the table in Management Studio and select Create-To new query editor... but all I get is the table structure.
How exactly do I get the values too?
One of the things I really like about the tools for MySQL that SQL Server is missing out of the box to be certain.
You can use a script to do it however.
You might also want to consider using something like Red-Gate SQL Compare and Red-Gate SQL Data Compare. They aren't cheap tools, priced at $395 each (for the standard editions), but there are 14 day free trials available for download, and they make copying schema and data from one SQL Server to another very easy.
If both are on the same machine (or on different machines but the servers are linked)
you can create the table with the script you can generate automatically and do this to copy the data:
INSERT INTO [destinationdb].[dbo].[destinationtable] SELECT *
FROM [originaldb].[dbo].[originaltable]
(Prepend [servername] to the database name if you'll be using linked servers)
Another option is to enable xp_cmdshell (do with care, it's relaxing security constraints) and use the bcp command line utility from the management studio to create copies you can then import into the other database/server. You can do that directly from the shell as well and do not need to enable xp_cmdshell in that case, of course.
it doesn't really create a "SQL script" but it does the job :
select the database in the object explorer
right click
select import/export data
follow the wizard
at the end of the process you can save the "integration service package" to reuse it
later you can modify the details by opening the .dtsx
(it will take care of security, and won't cost one more penny, it's seems we have to compete with other answers :) )
hope it helps.