Creating procedure won't recognize DB - sql-server

I'm trying to create and execute a procedure that creates some tables. It won't recognize my database.
USE [db1]
go
create procedure version_1 as
update db1
set ver=1
where ver=0;
create table Staff_Titles(
title nvarchar(100) not null,
title_description nvarchar(200) null,
[..]
go
It compiles even though the db1 from update db1 is underlined. So is ver=1 and ver=0. After I try to execute it, it says
invalid object name
at USE [DB1] again even though, it's inside the stored procedures...
I tried refreshing the database, I tried looking for Edit -> IntelliSense but I can't find it, I tried Ctrl + shift + R, nothing worked.

The IntelliSense is telling you that it can't find a table called db1 in the db1 database. Make sure the table exists or if it's in a different schema, make sure to include the schema, like this:
update db1.schmaname.db1
set ver=1
where ver=0;
If you are trying to store version data, you have to add a table and a field to store this information. You can not update fields on a database, as there are no fields directly at the database level. You can create a table called "Versions" with a field called "ver".
CREATE TABLE Versions
(
[Ver] [int] NOT NULL,
CONSTRAINT [PK_Versions] PRIMARY KEY CLUSTERED (Ver ASC)
)
Then when you run the procedure it could insert a record to indicate that the tables have been updated with that version. Something like this:
insert into Versions
values (1)
Then if you ever need to query for the latest version you could use:
select max(Ver) Ver from Versions

You might want to try and clear the intellisense cache if you "just" created that Database. Use the keystroke Ctrl-Shift-R or Ctrl-R.

Related

Undocumented SmoScriptOption: ScriptForAlter and ScriptForCreateDrop

scrp.Options.ScriptForAlter -- I suppose it scripts an ALTER TABLE instead of a CREATE TABLE
scrp.Options.ScriptForCreateDrop -- I'd guess it scripts a DROP TABLE and only afterwards a CREATE TABLE ?
My DB is fairly large and I'm still using Management Studio for script generation, so I'd like to know if someone else already found out the meaning of those options.

Make default value in field equal to the database name in SQL server 2014

Updated
I would like to create a database table that contains the database name for every record that gets created and concatenates it with an auto-incrementing number. Please see below what I am trying to do:
CREATE DATABASE TEST_1234_5678
GO
USE TEST_1234_5678
GO
CREATE TABLE TBL_ANALYSIS
(ID INT NOT NULL IDENTITY(1,1),
DATABASE_NAME VARCHAR(14) DEFAULT DB_NAME()
DESIRED_ID VARCHAR(20) DEFAULT DATABASE_NAME + CAST(ID AS VARCHAR)
);
I am unable to assign DESIRED_ID.
First of all, running CREATE DATABASE does not switch you to that context. If, for instance, I'm currently connected to My_DB and run your CREATE DATABASE command, the DB might be created, but I'll still be working on My_DB.
I only point that out because your question doesn't show that you're switching DB context, and that might be relevant, depending on how your server is set up.
CREATE DATABASE TEST_1234_5678
GO
USE TEST_1234_5678
GO
CREATE TABLE TBL_ANALYSIS
(ID INT NOT NULL IDENTITY(1,1),
DATABASE_NAME VARCHAR(14) DEFAULT DB_NAME()
)
GO
INSERT INTO TBL_ANALYSIS DEFAULT VALUES
GO
Depending on the error you're getting, this could be a number of different things. Assuming that you're in the right context and connected as a user with permissions, the error message you're getting could be extremely important to solve the issue. I would recommend ensuring that you're switching contexts, and if it still isn't working for you you might considering editing your question and posting the actual error message.
EDIT: After getting some more information from you, I understand that the issue is in trying to create a column with a default value
based on other columns in the table. This isn't something that is
supported in SQL Server, but you can use a computed column to get the
same information. Since this isn't a complex operation, you could do
something as simple as this:
CREATE DATABASE TEST_1234_5678
GO
USE TEST_1234_5678
GO
CREATE TABLE TBL_ANALYSIS
(
ID INT NOT NULL IDENTITY(1,1)
,DATABASE_NAME VARCHAR(14) DEFAULT DB_NAME()
,DESIRED_ID AS DATABASE_NAME + CAST(ID AS VARCHAR(14))
)
GO
INSERT INTO TBL_ANALYSIS DEFAULT VALUES
GO
SELECT * FROM TBL_ANALYSIS
GO

SQL IDENTITY autoincrement when 0 but still allow explicit inserts

I am dealing with this problem: I would like to have autogenerated identity in my table which is of type int
But, I would like to be able to explicitly set the identity. Now the real challenge is that this stuff is going through Entity Framework. I have my database with a IDENTITY(1,1) column, and IDENTITY_INSERT set to ON.
And whenever the Id is 0 (not specified) in newly created object, it inserts the very same 0. Any help appreciated, except offers to reconsider architecture (I will do that in any other case if this attempt fails).
And all this must work either on SQL CE, and SQL Server.
If you tell EF the primary key is database generated then it will not pass the id to the insert sql. You need to pass the ID so go with DatabaseGenerated.None.
But you want it to be an IDENTITY, so make it one in a migration script. You could change the CREATETABLE statement, adding identity: true to the column specification, or you can modify the table by running sql using the Sql() method
Now you need to modify the actual sql run during insert. The only way to do that is configure your model to use stored procedures then modify the sql generated in the Up migration for the insert procedures:
CREATE PROCEDURE [dbo].[My_Insert]
#Id int,
--ETC
AS
BEGIN
IF(Id > 0) SET IDENTITY_INSERT ON
INSERT --ETC
IF(Id > 0) THEN BEGIN
SET IDENTITY_INSERT OFF
SELECT Id
ELSE
SELECT SCOPE_IDENTITY() AS Id
END
END

SQL Server equivalent of MySQL Dump to produce insert statements for all data in a table

I have an application that uses a SQL Server database with several instances of the database...test, prod, etc... I am making some application changes and one of the changes involves changing a column from a nvarchar(max) to a nvarchar(200) so that I can add a unique constraint on it. SQL Server tells me that this requires dropping the table and recreating it.
I want to put together a script that will do the table drop, recreate it with the new schema, and then reinsert the data that was there previously all in one go, if possible, just to keep things simple for use when I migrate this change to production.
There is probably a good SQL Server way to do this but I'm just not aware of it. If I was using Mysql I would mysqldump the table and its contents, and use that as my script for applying that change to production. I can't find any export functionality in SQL server that will give me a text file consisting of inserts for all data in a table.
Use SQL Server's Generate Scripts command
right click on the database; Tasks -> Generate Scripts
select your tables, click Next
click the Advanced button
find Types of data to script - choose Schema and Data.
you can then choose to save to file, or put in new query window.
results in INSERT statements for all table data selected in bullet 2.
No need to script
here are two ways
1 use alter table ....alter column.....
example..you have to do 1 column at a time
create table Test(SomeColumn nvarchar(max))
go
alter table Test alter column SomeColumn nvarchar(200)
go
2 dump into a new table while converting the column
select <columns except for the columns you want to change>,
convert(nvarchar(200),YourColumn) as YourColumn
into SomeNewTable
from OldTable
drop old table
rename this table to the same table as the old table
EXEC sp_rename 'SomeNewTable', 'OldTable';
Now add your index

Visual Studio 2010 deploys views too late in deploy process

I have a database project in my VS2010 solution. I recently changed a view and and changed a number of functions to use this view instead of going directly against a table.
But now when I deploy I get errors on most of these functions because the column asked for does not exists in the view yet.
The update of the view happends later than the update of UDF's. Is there any way to change this behaviour?
Wouldn't the best thing be if the deploy script updated in this order: tables, views, SP and UDF. It seems like tables is updated first, but the views are just thrown in somewhere in the middle of the deploy script.
Since UDFs may be used in views, and views may be used in UDFs, it would have to analyse all of them to determine a coherent deployment order - it would have to parse all of the SQL. And who knows what it's to do if you have dependencies on other databases.
Edit
There's no documented/supported way to force a deployment order, so far as I can see. With some minimal testing, it appears to me that UDFs (at least table valued) are always deployed before views.
Edit 2
Even stranger, it turns out it does do the dependency analysis. Looking at the .dbschema output file for a db project, I can see it produces a <Relationship Name="BodyDependencies"> element for the function, that does list the view/columns it depends on. But the deployment sql script still puts the view later on. Curious.
Edit 3
Probably final edit. I think, in general, that the problem is unsolvable. (Admittedly, the following only errors because I've specified schemabinding). If the old function definition relies on the old view definition, and the new function definition relies on the new view definition, there's no right way to alter the database using ALTERs:
create table dbo.T1 (
ID int not null,
C1 varchar(10) not null,
C2 varchar(10) not null,
C3 varchar(10) not null
)
go
create view dbo.V1
with schemabinding
as
select ID,C1,C2
from dbo.T1
go
create function dbo.F1()
returns table
with schemabinding
as
return select ID,C1,C2 from dbo.V1 where ID=1
go
alter view dbo.V1
with schemabinding
as
select ID,C1,C3
from dbo.T1
go
alter function dbo.F1()
returns table
with schemabinding
as
return select ID,C1,C3 from dbo.V1 where ID=1
go
result:
Msg 3729, Level 16, State 3, Procedure V1, Line 4
Cannot ALTER 'dbo.V1' because it is being referenced by object 'F1'.
Msg 207, Level 16, State 1, Procedure F1, Line 5
Invalid column name 'C3'.

Resources