Not able to run sql-script for database in Visual Studio - sql-server

I am trying to learn MVVM Pattern for WPF Applications in Visual Studio.
To this end I am doing an online course, which provides the source code for the course project under the following address:
https://github.com/briannoyes/WPFMVVM-StarterCode
I downloaded the project code and opened the project in Visual Studio.
So far so good.
Then I am supposed to create an empty database and run the ZzzDatabaseGen.sql. file, which was also provided under the above-mentioned link.
So I did the following steps:
Choose "Project"
Choose "Add New Item"
Select "Service-based Database"
In the Name area, I typed: Zza.mdf
Choose Add
Then I opened the file ZzzDatabaseGen.sql and executed it.
I receive an error message telling me that the database "Zza" doesn't exist.
What do I have to do to create a database, connect it to my project and be able to run the ZzzDatabaseGen.sql script so that all the tables are created?

Before running the script file you have to create the database in your SQL Server instance.
So, for example, using the SQL Server Object Explorer in VS you can access all your local SQL Server Express instances.
Here, you can select the desired instance and click "New query".
To create a database for your purpose you can simply run this code:
CREATE DATABASE [Zza] ON PRIMARY
( NAME = N'Zza', FILENAME = N'\Zza.mdf')
LOG ON
( NAME = N'Zza_log', FILENAME = N'\Zza_log.ldf')
GO
Of course you have to write the correct path to the mdf file you would like to create.
After that you can run the ZzzDatabaseGen.sql script to create the tables and insert all the data.

Right-click on the Service-based database file (Zza.mdf) that you created in the Solution Explorer in Visual Studio and choose "Open". This should bring up the Server Explorer (View->Server Explorer).
Then you right-click on the Zza.mdf node in the server explorer and choose "New query". You should then be able to run the queries in the query window.
Press the green play arrow once you have pasted in the queries from the ZzzDatabaseGen.sql script.

Related

Visual Studio schema compare can't find generated script

I am performing SQL Server schema comparison using Visual Studio 2017. I am pressing on "Generate script" button of Schema Compare utility and see the message
"Update scripts generated successfully"
However, I am unable to see the generated script. Any idea where this went or if it failed?
According to this page "The generated script appears in a new Transact-SQL Editor window".
When this didn't work for me, i closed all open windows other than the schema compare window and re-checkmarked all differences in the list (i had un-checked some). After doing this and running "Generate Script" again, Visual Studio did actually open a new window with the script (The filename was "C:\Users\me\AppData\Local\Temp\MyDbName_Update1.publish.sql").
I've noticed that if SSMS is running , SSDT won't generate Schema Compare script. As soon as I close SSMS and try to generate script again SSDT creates one successfully.
Instead of direct compare from connection string, generate schema file and then compare that file
do this steps:
in visual Studio Go To Sql Server Object Explorer
Right Click on database name
Select Extract Data Tier Application
select location for file save
select Schema Only
deselct all checkbox option or check as your compare requirement
do the same for both source database and target database
then
when compare schema select option Data-Tier appication file option

Visual Studio 2013 CLR Stored Procedures

I have been working with earlier versions of Visual Studio (VS2008) in conjunction with SQL Server 2008.
Recently my organization moved to VS2013 and SQL Server 2012. I am finding the database interfaces in VS2013 quite a bit different than what was present in VS2008.
My question is basically if anyone knows of an article or referenced that details how to do what is described here:
http://yassershaikh.com/how-to-create-a-clr-stored-procedure-using-c-and-visual-studio/
(Specifically the deployment of the DLL to a SQL Server 2012 database).
But using VS2013 and SQL Server 2012.
(In case of minor differences between the info here and what you are seeing, I am running Visual Studio 2012 Update 4 with SSDT 11.1.31203.1 on Windows 8)
In VS 2008 / VS 2010 you could "Deploy" a database project (i.e. .csproj / .dbproj file, respectively) to get the assembly and T-SQL wrapper objects into SQL Server. The newer versions of Visual Studio still have "Deploy" options in the "Build" menu (at least VS 2012 has them in for both the solution and the project), but they do not do anything. You now have a .sqlproj file and the way to get the solution/project into the database is to use the "Publish {SolutionName}..." option in the "Build" menu.
More on publishing in a moment. First, here is some info that might help:
SQL Server / SSDT
SQL Server projects (i.e. .sqlproj) are explicitly handled via SQL Server Data Tools (SSDT)
Visual Studio / SSDT, by default, points to a local SQL Server database. The preference had been to use SQL Server Express Edition (also see SQL Server Express User Instances), but starting in SQL Server 2012 there was a new variation of Express Edition called "Express Edition LocalDB" (commonly referred to as just "LocalDB")
Introducing LocalDB, an improved SQL Express
Local Data Overview (SQL Server Express vs LocalDB)
SQL Server Express LocalDB
How to: Upgrade to LocalDB or Continue with SQL Server Express
The SQL Server Express LocalDB instance is located in the following path:
C:\Users\{User Name}\AppData\Local\Microsoft\Microsoft SQL Server Local DB\Instances\{Instance Name}
You connect to LocalDB using the following convention:
(localdb)\{Instance Name}
When a new solution is created, a folder to house the database-per-project files is created in:
C:\Users\{User Name}\AppData\Local\Microsoft\VisualStudio\SSDT\{Solution Name}
Within that ...\SSDT\{Solution Name} folder will be at least two files per project:
{Project Name}.mdf
{Project Name}.ldf
If you add more projects to that solution, new files will appear in that ...\SSDT\{Solution Name} folder
The solution folder and per-project-database files are created as you initial create the new project, whether you ever use them or not ;-)
Visual Studio
There are 3 main tabs within "Project Properties" that will control what is scripted and possibly published
Project Settings
Under "Output Types", the "Create script (.sql file)" check-box controls whether or not the Build operation creates the SQL script to drop and recreate DB with at least the Assembly:
{Build Output Path}\{Build Output File Name}_Create.sql
SQL CLR
The "Generate DDL" check-box controls whether or not to create the T-SQL wrapper objects:
CREATE {Object Type} {Object Name} ... AS EXTERNAL NAME {Assembly Name}.{Class Name}.{Method Name OR "name" property, if specified, in the [SqlProcedure] / [SqlFunction] / [SqlUserDefinedAggregate] / [SqlUserDefinedType] / [SqlTrigger] attribute}
The "Include Symbols" check-box controls whether or not to import the {Assembly Name}.pdb file into SQL Server (in sys.assembly_files); the .pdb file will be created in the {Build Output Path} even if this option is unchecked.
Build
These are not SQLCLR specific
"Build output path:" controls where the finalized DLL, PDB, SQL, and DACPAC files will be located
"Build output file name:" controls the name of the SQL scripts and the DACPAC file
The Deploy tab has been removed
This tab had a check-box for "Deploy Code" that would include the .pdb file and the source code (.cs and/or .vb.) files as ALTER ASSEMBLY {Assembly Name} ADD FILE FROM 0x... AS {File Name} entries. This option seems to have been replaced by the "Include Symbols" check-box on the SQL CLR tab which only includes the .pdb file and not the source code files. [I see this as an improvement as I never liked the idea of deploying the source code since some people (maybe many?) promoted all of that stuff into Production :-(.]
Selecting the "Publish {Solution Name}..." option in the "Build" menu will bring up a "Publish Database" dialog asking for database details. For "Target database connection:", click the "Edit..." button to the right. A dialog for "Connection Properties" will open. There will be a drop-down for "Server name:" that you can either pull down to discover instances or just type in the name. If you have a default instance running locally, you should be able to just type in "(local)" [but without the double-quotes]. The default authentication in the next section, "Log on to the server", is "Use Windows Authentication". If you are using a SQL Server login then you can select the other radio button and enter in the "User name:" and "Password:" details. The next section is "Connect to a database" and the top radio-button for "Select or enter a database name:" is already selected. There is a drop-down that, if pulled down, will populate with a list of databases on the server that was selected (or entered) in the "Server name:" drop-down. Select, or enter in, the desired database and click the "Test Connection" button on the bottom left of the dialog. You should get a pop-up stating "Test connection succeeded" so click the OK button in that pop-up and then the "OK" button in the "Connection Properties" dialog.
Now you can:
Click the "Save Profile As..." button (bottom left of the "Publish Database" dialog)
Next time, just click the "Load Profile..." button (it will have the visible settings as well as whatever is configured within the "Advanced..." button)
Click the
"Publish" button to push immediately to the database
"Generate Script" button to simply create the publication SQL script:
{Build Output Path}\{Build Output File Name}.publish.sql
You can also deploy the DACPAC file: Data-tier Applications
Just FYI: the base T-SQL pieces to create the objects can be found in the following location, but you should be careful not to run the SQL script as is since the items are not in a runnable order:
{ProjectDir}\obj\{Configuration Name}\{Assembly Name}.generated.sql
For several of the Visual Studio-specific references above, those are the names of the fields that you see in the UI. Their equivalents within the .sqlproj file are:
{Project Name} == <Name>
{Assembly Name} == <AssemblyName>
{Build Output Path} == <OutputPath>
{Build Output File Name} == <SqlTargetName>
"Create script (.sql file)" check-box == <GenerateCreateScript>
"Generate DDL" check-box == <GenerateSqlClrDdl>
"Include Symbols" check-box == <GenerateSqlClrSymbols>
For more information on SQLCLR in general, I am writing a series on SQL Server Central (free registration required) called "Stairway to SQLCLR". (Currently there are only 4 articles published out of what will eventually be about 12. The next one, coincidentally, is on Development & Visual Studio :-) )
EDIT:
One interesting, and mostly good, new feature is the verification of dependencies to give compile-time errors of T-SQL objects, just like the .Net languages have. The downside is that there doesn't seem to be a way to disable it. This doesn't usually affect SQL CLR projects, except in the case of CLR-based triggers. The problem here is that if you have the "Generate DDL" option enabled, in order to do the "Build" you need to have the Target and Event properties of the SqlTrigger attribute filled out. And, the model (i.e. database model) verification step will check to make that the table named in the Target property actually exists. If not, you will get an unresolved reference to object error. The only way to get passed this, it seems, is to a) have that object in your project, or b) have that object in a project that is referenced as a "Database Reference":
If you have only a few tables needing to be referenced, it could be easiest to just generate their CREATE TABLE statements in SSMS, and then right-click on the project in Solution Explorer (or go to the "Project" menu) and go to "Import -> Script (*.sql)...".
If you have lots of triggers on lots of different tables, then you can:
Create a new project in the same solution:
Right-click on project name in Solution Explorer (or go to Project menu)
Go to "Import ->"
Select "Database..."
Enter the connection info
Extract the schema to a .dacpac file:
Go to "SQL Server Object Explorer" in VS
Select your server and expand the list of databases
Right-click on the database in question
Select "Extract Data-tier application..."
Choose a location and enter in a file name (in the "File on disk" field).
Click the "OK" button
Whichever method you chose, you need to add it as a "Database Reference":
Right-click on the "References" folder in your main project (or go to the "Project" menu)
Go to "Add Database Reference..."
Depending on which method you chose, pick either "Database projects in the current solution" or "Data-tier Application (.dacpac)"
Chose the newly created project or .dacpac file
For the "Database location:" drop-down, you must select "Same database"!
Click the "OK" button
Keep in mind:
If importing individual tables you will likely need to also import any tables referenced in any foreign keys that might be on any table being imported
The full CREATE TABLE DDL will be generated in the _Create script each time, but the "Publish" script will only contain DDL for changes, and so if there are no changes in the definition of the table, then the table DDL will not appear in the "Publish" .sql script. Changes are determined by comparing the table definition in your project or .dacpac file with the destination database defined in the Connection Settings of the "Publish" dialog / wizard.
The upgrade from Visual Studio 2010 to 2013 converted the project containing SQL CLR functions to a SQL Server project which would no longer compile or deploy. Worse, SQL Server projects seem to now require dependencies on some database for deployment. Since the CLR functions don’t reference the database, dependencies are unnecessary.
The solution was to convert the project back to a C# class project and use SQL Server to create the assembly and add DLLs to the library. The SQL had been written a couple of years ago and it was possible to continue to use the same Asymmetric key.
If there is a way to make a VS SQL Server project handle CLR functions without database dependencies, I would like to know what it is.

How to generate and connect to database from entity data model in Visual Studio 2010?

I read a few of the corresponding questions here but none of them seems to solve my problem.
I have a .edmx file. I want to generate a database from this model, so I do the following:
Right-click on the entity data model, then Generate Database From Model. Generate Database Wizard appears and asks where to save a generated .sql file. I can only click on Finish.
Now I have an sql file. I run the script - still inside Visual Studio - and it says everything is ok, rows affected etc.
So I suppose I have a database now. (Although I don't know the path of the .mdf file, nor can I look into it to see if the tables have been generated correctly, but that's not the point.)
Visual Studio says I'm connected, though I can't see this database in Server Explorer.
So I run the program, and an exception appears:
EntityExcpetion was unhandled. The underlying provider failed to open.
What's the story with this?
When in your .edmx design window, click anywhere outside of an entity, and view the properties window (F4 is it is not visible). In the properties window, look at the connection string value, and determine if it is valid. You can also see where it is connecting, and thereby confirm the tables are generated correctly.
The connection string is also saved in the App.Config file.
It seems like you are logged in to the database using Visual Studio, but the login does not have all the details correct in the App.Config or there is a permissions issue between the two logins.
When you run your query in Visual Studio, does it ask you to connect to SQL Server? if so, what is the server you are connecting too? I'm thinking you are creating your database in a different server that the one in your project's connection string.

Visual studio 2010 sql project - how to run?

I have a SQL project in my .Net project in Visual Studio 2010. I added it to my solution because I thought it will help me to create all the database objects in more environment without difficulties.
My scope is to create/define the database objects (tables and stored procedures) in more computers, easily.For this purpose I created an Sql project in visual studio and I added for each table and stored procedure the creation script in this project. Now I have 30 scripts and I'd like to run it on a new sql instance.
If I open each sql file I have, in visual studio, an toolbat that allows me to tun the opened file on a sql instance (I have an connect button) and this generates the proper object (table or SP).
The question is: how do I do to run all the files in this project in one click. How to create all the objects in one click? Now I have about 30 scripts to run, and I need a proper way.
The way I tried to do it was to set as default project the sql project and to press run (F5), but then I got some strange compilation errors in sql files, errors witch didn't was there when I run (execute) each script individually.
Here is the right click menu for this project (No Run, Publish or something else!):
I tried to use from that menu the Deploy command. The bad news (for me) is that I got this on that command:
I don't have any error in my sql scripts, each one runs correctly.
Thank you.
Use need to deploy your project onto a database thus use the Deploy menu item.
The way database projects work, is that they compare the schema in the project to the schema at the destination.
What this means is you shouldn't have an use statements, or alter statements, ect...
What does one of those procs look like that is throwing the error?

Can't gain access to my database created though Visual Studio?

I have created a database emailDatabase, its stored in
C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA
In Visual Studio, I use the Server Explorer, click the add new connection button.
The add connection dialog box appears.
Under server name I use the dropdown box and select DEV-5\SQLEXPRESS. I use Windows authentication.
In the Connect to section at the bottom, the dropdown displays: Master, Model, msdb and tempdb and does not display my emailDatabase.
So I select Attach Database File and click browse and follow
local C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA
and select my email database.
The following error occurs :
emailDatabase
You don not have permission to open this file.
Contact file owner or an administrator to obtain permission.
I think my problem is i saved my database wrong, I need to make a back up or something like that. if that's the case please tel me how to make a backup and so on. I really need to move forward from this problem.
When I created my database I right-clicked on databases in SQL Server Management Studio and said new database, then I added columns with a query. then file save all.
How can I get a copy of my database file with all the permissions I need to use it in visual Studio??
When you create a database on the server (using SQL Server Management Studio), you don't have to (and should not!) fiddle around with the database file(s) anymore - let the server handle that for you.
Instead: do a Add Connection in Visual Studio and then specify the server instance (DEV-5\SQLEXPRESS) and the database name (emailDatabase) in your connection dialog.
With this, you're connecting and using a SQL Server database the way it's intended to be used - on the SQL Server instance itself. This is much easier, and much less hassle, than having to struggle with "free-floating" .mdf files and attaching them to your solutions and stuff like that....
So here - fill in DEV-5\SQLEXPRESS into your "Server name" dropdown, and then use the "Select or enter database name" option and enter your database name (or pick it from the dropdown) - it should be there!
DO NOT use the "Attach a database file" option - this is the free-floating .mdf "feature" which is rather clumsy and hard to use and error-prone - again: I recommend not using that...
Had the same problem and I realised the problem was not in VS2010 but my SQLserver.My instance name is OMAFANO ,and that's what my MSSQL connected to under Server Name. Now here's the catch,click on that and connect to OMAFANO\SQLEXPRESS and create all your databases and tables there if you want them to show up in VS2010 the way u stated up there. So under server name in VS2010 also write INSTANCENAME\SQLEXPRESS if you want to see your newly created databases etc. Take a look at the picture:
I thought I had it figured out but problems continue to pop up. So ...
IGNORE EVERYTHING BELOW THIS LINE.
After hours of tinkering I finally figured out how to use SSMS to connect to a SQLServer 2008 database that was created in VS2010, and it is relatively simple. But from the number of unanswered questions all over the place not well documented. Here's how to do it:
In VS right click the project in SolutionExplorer and select Add new item then select Data then SQLServer database. It will prompt you to save it in the app_data folder and create the folder for you if it doesn't exist.
Find the Ssms.exe file (on my system it's in C:\Program Files\Microsoft SQL Server\100\Tools\Binn\VSShell\Common7\IDE
Right click Ssms.exe and select Run as administrator.
After SSMS opens you can attach the project MDF. It will now be on your list of databases. The database name is a GUID.
You can even run aspnet_regsql against the database to add the Membership tables and sprocs.
IMPORTANT! You can manage this database with EITHER SMSS OR VS but not both at the same time. If you mess with the database from within VS using ServerExplorer you will break the SSMS connection. To fix that you will need to detach and reattach the database.
Run Your Visual studio As Administrator
Go to Visual Studio instance i.e C#,C++ etc
Right click > Run as Administrator
Then now It may work
To connect to a ssms2014 database from visual studio 2013, in the new connection wizard I had to change 'data source' from 'ms sql server database file' to '.net framework data provider for sql server..'. Then I was able to enter [computer name][username] for windows authentication.
I had the same issue, you just type your local server name "sara-PC" instead of
"sara-PC\SQLEXPRESS"
Now you can access your database easily, you can see it in your dropdownlist.
And also please dont use file access method to attatch database, thats not good way.
Also you can put ~....\Data and ~...\log file wherever you want by setting default location using server->rightclick->properties->Database settings.
Definitely this solves your issue.

Resources