Implicit conversion from data type datetime to int is not allowed. Use the CONVERT function to run this query - sql-server-2008r2-express

alter table Garantor alter column [Birth Date] int

Try something like this (you'll need to create a new column, update it with a conversion, drop the old one then rename the new one with old one's name)
ALTER TABLE dbo.Garantor
ADD newBirthDate int NOT NULL DEFAULT 0 -- NULL and DEFAULT as required
GO
UPDATE dbo.Garantor
SET newBirthDate = CAST([Birth Date] AS int) -- or CONVERT function, it will do the same
GO
ALTER TABLE dbo.Garantor
DROP COLUMN [Birth Date]
GO
SP_RENAME 'dbo.Garantor.newBirthDate', 'dbo.Garantor.[Birth Date]'
GO

Convert does not work for me.
Cast does not work either.
To change the data type of a column, here is the code that worked.
Change the "date" type to the "int" type, keeping only the year.
This works for me:
ALTER TABLE [dbo].[Garantor]
ADD [newBirthDate] int NOT NULL DEFAULT 0
GO
UPDATE [dbo].[Garantor]
SET [newBirthDate] = DATEPART(yyyy,[Birth Date])
GO
ALTER TABLE [dbo].[Garantor]
DROP COLUMN [Birth Date]
GO
SP_RENAME 'dbo.Garantor.newBirthDate', 'dbo.Garantor.[Birth Date]'
GO
An alternative solution is:
= YEAR([Birth Date])
And if you have an index in your table:
ALTER TABLE [dbo].[Garantor]
ADD [newBirthDate] int NOT NULL DEFAULT 0
GO
UPDATE [dbo].[Garantor]
SET [newBirthDate] = DATEPART(yyyy,[Birth Date])
GO
ALTER TABLE [dbo].[Garantor] DROP CONSTRAINT [UQ__Garantor__1C123681D17FE31B] -- [UQ__Garantor__1C123681D17FE31B] change with your
GO
ALTER TABLE [dbo].[Garantor]
DROP COLUMN [Birth Date]
GO
SP_RENAME 'dbo.Garantor.newBirthDate', 'dbo.Garantor.[Birth Date]'
GO
ALTER TABLE [dbo].[Garantor] ADD UNIQUE NONCLUSTERED
(
[Birth Date] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO

Related

How to create a new row for the same record after modifying one of the records and updating a new date?

I am trying to make it so that when I change a description from my records, the table will automatically add a new record with a new PRODUCTKEY value which contains the same data as the previous records but with the new description. This new record will also update the dates so that the new start date will become the previous end date, and the new end date will become the SYSDATE which is the date in which the record was last modified.
I have merged my tables together but MERGING only changes all the dates and doesn't add a new record. I do not know what to do anymore.
Here's an example:
Here's my code:
CREATE TABLE PRODUCT_DIM
(
PRODUCTKEY integer NOT NULL,
PRODUCTID integer,
PRODUCTDESCRIPTION VARCHAR2(50 BYTE),
PRODUCTLINEID integer,
PRODUCTLINENAME VARCHAR2(50 BYTE),
CONSTRAINT PRODUCT_DIM_PK PRIMARY KEY (PRODUCTKEY)
);
ALTER TABLE PRODUCT_DIM
ADD EFF_START_DATE DATE DEFAULT '27-NOV-17';
ALTER TABLE PRODUCT_DIM
ADD EFF_END_DATE DATE DEFAULT '27-NOV-17';
CREATE SEQUENCE PRODUCT_KEY_SEQ
MINVALUE 1001
START WITH 1001
INCREMENT BY 1
CACHE 25;
INSERT INTO PRODUCT_DIM
(PRODUCTKEY, PRODUCTID, PRODUCTDESCRIPTION, PRODUCTLINEID, PRODUCTLINENAME)
SELECT PRODUCT_KEY_SEQ.NEXTVAL, nvl(to_char(p.PRODUCTID), 'Undefined'), nvl(to_char(p.PRODUCTDESCRIPTION), 'Undefined'),
nvl(to_char(p.PRODUCTLINEID), 'Undefined'), nvl(to_char(pl.PRODUCTLINENAME), 'Undefined')
FROM PRODUCTLINE_T pl, PRODUCT_T p
WHERE p.PRODUCTLINEID = pl.PRODUCTLINEID;
INSERT INTO PRODUCT_DIM
(PRODUCTKEY, PRODUCTID, PRODUCTDESCRIPTION, PRODUCTLINEID, PRODUCTLINENAME)
VALUES (PRODUCT_KEY_SEQ.NEXTVAL, -99, 'Undefined', -99, 'Undefined');
CREATE TABLE PRODUCT_DIM_HIS
(
PRODUCTKEY integer NOT NULL,
PRODUCTID integer,
PRODUCTDESCRIPTION VARCHAR2(50 BYTE),
PRODUCTLINEID integer,
PRODUCTLINENAME VARCHAR2(50 BYTE),
EFF_START_DATE DATE,
EFF_END_DATE DATE,
CONSTRAINT PRODUCT_DIM_HIS_PK PRIMARY KEY (PRODUCTKEY)
);
INSERT INTO PRODUCT_DIM_HIS
(PRODUCTKEY, PRODUCTID, PRODUCTDESCRIPTION, PRODUCTLINEID, PRODUCTLINENAME, EFF_START_DATE, EFF_END_DATE)
SELECT PRODUCT_KEY_SEQ.NEXTVAL, nvl(to_char(p.PRODUCTID), 'Undefined'), nvl(to_char(p.PRODUCTDESCRIPTION), 'Undefined'),
nvl(to_char(p.PRODUCTLINEID), 'Undefined'), nvl(to_char(pl.PRODUCTLINENAME), 'Undefined'),
to_date(o.ORDERDATE), to_date(o.FULFILLMENTDATE)
FROM PRODUCTLINE_T pl, PRODUCT_T p, ORDER_T o, ORDERLINE_T ol
WHERE p.PRODUCTLINEID = pl.PRODUCTLINEID
AND o.ORDERID = ol.ORDERID
AND ol.PRODUCTID = p.PRODUCTID;
MERGE INTO PRODUCT_DIM_HIS pdh
USING PRODUCT_DIM pd
ON (pdh.PRODUCTID = pd.PRODUCTID)
WHEN MATCHED THEN
UPDATE SET
EFF_START_DATE = pd.EFF_START_DATE,
EFF_END_DATE = SYSDATE;
You need to write procedural code to manage this. There are various options.
One would be to have a stored procedure to wrap the update and insert implementation. This is probably the cleanest approach; it is definitely the approach to take if you need to do this operation in bulk.
Alternatively write a trigger which populates the history table when the source table is changed.
If you have Enterprise Edition 11.2.0.4 or later you could use the built-in Flashback Data Archive feature which maintains history tables transparently. Find out more.
Which approach is best depends on how you want to use the history table.

ssdt project in visual studio 2013 - Deploy alterscript for not empty Tables

I hoop you can Help me.
I use the Skriptgeneration in the Schemacomparetool of Visual Studio 2013 SDDT Project. My Problem is I need to Update a Table that's not empty.
The Schemacompartool make this:
/*
The type for column Bundesland in table [dbo].[Arbeitsfreiertag] is currently VARCHAR (50) NULL but is being changed to BIGINT NULL. Data loss could occur.
*/
IF EXISTS (select top 1 1 from [dbo].[Arbeitsfreiertag])
RAISERROR (N'Rows were detected. The schema update is terminating because data loss might occur.', 16, 127) WITH NOWAIT
GO
...
PRINT N'Altering [dbo].[Arbeitsfreiertag]...';
GO
ALTER TABLE [dbo].[Arbeitsfreiertag] ALTER COLUMN [Bundesland] BIGINT NULL;
I need also the change skript like Managment Studio Designer change:
/* To prevent any potential data loss issues, you should review this script in detail before running it outside the context of the database designer.*/
BEGIN TRANSACTION
SET QUOTED_IDENTIFIER ON
SET ARITHABORT ON
SET NUMERIC_ROUNDABORT OFF
SET CONCAT_NULL_YIELDS_NULL ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
COMMIT
BEGIN TRANSACTION
GO
CREATE TABLE dbo.Tmp_Arbeitsfreiertag
(
ID bigint NOT NULL,
Bundesland bigint NULL,
Name varchar(50) NOT NULL,
ArbeitsfreiertagTyp bigint NOT NULL,
Beginn datetime NOT NULL,
Beschreibung varchar(200) NULL,
Ende datetime NULL,
Land bigint NOT NULL,
Wiederholend int NOT NULL
) ON [PRIMARY]
GO
ALTER TABLE dbo.Tmp_Arbeitsfreiertag SET (LOCK_ESCALATION = TABLE)
GO
IF EXISTS(SELECT * FROM dbo.Arbeitsfreiertag)
EXEC('INSERT INTO dbo.Tmp_Arbeitsfreiertag (ID, Bundesland, Name, ArbeitsfreiertagTyp, Beginn, Beschreibung, Ende, Land, Wiederholend)
SELECT ID, CONVERT(bigint, Bundesland), Name, ArbeitsfreiertagTyp, Beginn, Beschreibung, Ende, Land, Wiederholend FROM dbo.Arbeitsfreiertag WITH (HOLDLOCK TABLOCKX)')
GO
DROP TABLE dbo.Arbeitsfreiertag
GO
EXECUTE sp_rename N'dbo.Tmp_Arbeitsfreiertag', N'Arbeitsfreiertag', 'OBJECT'
GO
ALTER TABLE dbo.Arbeitsfreiertag ADD CONSTRAINT
PK_Arbeitsfreiertag PRIMARY KEY CLUSTERED
(
ID
) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
COMMIT
I need a option to set this in ShemaCompartool.
I hope you understand my question.
Thanks Steffen
I think the problem is that your primary data type is NVARCHAR and you want to change it to BIGINT. In general scenario it will fail as you can't convert any string into integer.
What you need to do is to manually create a pre-deployment and post-deployment scripts and handle data conversion there. The script should look something like this:
--This is pre-deployment script
-- data backup into temp table
PRINT 'Backup data from dbo.Arbeitsfreiertag'
SELECT * INTO tmp_Arbeitsfreiertag from dbo.Arbeitsfreiertag
GO
PRINT 'TRUNCATE TABLE dbo.Arbeitsfreiertag'
TRUNCATE TABLE dbo.Arbeitsfreiertag
GO
--This is post-deployment script
--copy data from temp table into main table
PRINT 'Copy data from temp table tmp_Arbeitsfreiertag into main table'
INSERT INTO dbo.Arbeitsfreiertag (ID, Bundesland, Name, ArbeitsfreiertagTyp, Beginn, Beschreibung, Ende, Land, Wiederholend)
SELECT ID, CONVERT(bigint, Bundesland), Name, ArbeitsfreiertagTyp, Beginn, Beschreibung, Ende, Land, Wiederholend
FROM tmp_Arbeitsfreiertag WITH (HOLDLOCK TABLOCKX)
GO
IF ((SELECT COUNT(1) FROM tmp_Arbeitsfreiertag) = (SELECT COUNT(1) FROM Arbeitsfreiertag))
BEGIN
PRINT 'DROP TABLE tmp_Arbeitsfreiertag'
DROP TABLE tmp_Arbeitsfreiertag
END
GO

How to use NEWSEQUENTIALID() after a table has already been created and has data?

Could anyone help me with this please. I have a table that's not unique (as I'm rummaging through old databases of my predecessor.)
I would like to assign it to the "ID" field within the Fruits table I have.
I'd like to go ahead and get the NEWSEQUENTIALID() to be setup so I can see all what I'm working with.
Assuming ID is of type uniqueidentifier, you can create another column with sequential guids as default.This will populate the values in that column. After that you may copy these values to your id column and then drop the tmp column. Once all data is in, then specify defaults for your id column. See SQL Script below :
--create a new column with default as sequential ids
USE [BASKET]
ALTER TABLE [FRUITS]
ADD [TMPID] UNIQUEIDENTIFIER NOT NULL CONSTRAINT DF_TMPID DEFAULT NEWSEQUENTIALID()
GO
--update existing id column values with the newly created values
UPDATE [FRUITS] SET ID = TMPID GO
--remove constraint
ALTER TABLE [FRUITS] DROP CONSTRAINT DF_TMPID GO
--remove the temp column
ALTER TABLE [FRUITS] DROP COLUMN TMPID GO
--specify defaults for newly inserted defaults
ALTER TABLE [FRUITS] ADD DEFAULT NEWSEQUENTIALID() FOR ID
--or--
ALTER TABLE [FRUITS] ADD CONSTRAINT DF_ROWGUID DEFAULT NEWSEQUENTIALID() FOR ID;
CREATE PROCEDURE [dbo].[uspGetSequentialGuid]
AS
DECLARE #SequentialGuids as Table ( SequentialGuid uniqueidentifier DEFAULT NEWSEQUENTIALID() PRIMARY KEY,InitDate datetime )
BEGIN
INSERT INTO #SequentialGuids(InitDate) Values(GETDATE());
END
SELECT SequentialGuid from #SequentialGuids
GO
CREATE PROCEDURE [dbo].[uspGetSequentialGuids](#RequiredGuids as int)
AS
DECLARE #SequentialGuids as Table ( SequentialGuid uniqueidentifier DEFAULT NEWSEQUENTIALID() PRIMARY KEY,InitDate datetime )
Declare #Counter int
SET #Counter = 0
While #Counter < #RequiredGuids
BEGIN
INSERT INTO #SequentialGuids(InitDate) Values(GETDATE());
SET #Counter = #Counter + 1
END
SELECT SequentialGuid from #SequentialGuids
GO

Linq making primary key system.nullable<int> not just int

I'm mapping my database into base object with Linq to SQL. I drag all the tables into my dbml and they all setup nicely. I save the dbml and it creates the classes that represent the tables, etc.
In my database I have a table as such:
CREATE TABLE [dbo].[BidNames](
[BidNameID] [int] IDENTITY(1,1) NOT NULL,
[CustomerID] [int] NOT NULL,
[BidName] [varchar](75) NOT NULL,
CONSTRAINT [PK_BidNames] PRIMARY KEY CLUSTERED
(
[BidNameID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
The BidNameID field is clearly a primary key and obviously NOT NULL. Linq, however defines BidNameID like this:
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_BidNameID", DbType="Int")]
public System.Nullable<int> BidNameID
{
get
{
return this._BidNameID;
}
set
{
if ((this._BidNameID != value))
{
if (this._BidName1.HasLoadedOrAssignedValue)
{
throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();
}
this.OnBidNameIDChanging(value);
this.SendPropertyChanging();
this._BidNameID = value;
this.SendPropertyChanged("BidNameID");
this.OnBidNameIDChanged();
}
}
}
Where BidNameID is defined as System.Nullable. All the other tables in my database resolve correctly so I'm left wondering why this is happening. Any ideas?
Thanks in advance.
EDIT
I have discovered that this problem is related to another table. If I drop the Bids table from my dbml and re-save, the BidNameID column correctly resolves to int. If I put the Bids table back and save it goes back to Nullable. The Bids table has a foreign key into the BidNames table but the data is clean. Here is the structure of the Bids table:
CREATE TABLE [dbo].[Bids](
[BidID] [int] IDENTITY(1,1) NOT NULL,
[CustomerID] [int] NOT NULL,
[ItemID] [int] NOT NULL,
[Amount] [money] NOT NULL,
[BidName] [varchar](75) NOT NULL,
[BidTime] [datetime] NOT NULL,
[BidNameID] [int] NULL,
CONSTRAINT [PK_Bids] PRIMARY KEY CLUSTERED
(
[BidID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
ALTER TABLE [dbo].[Bids] WITH CHECK ADD CONSTRAINT [FK_Bids_BidNames] FOREIGN KEY([BidNameID])
REFERENCES [dbo].[BidNames] ([BidNameID])
GO
ALTER TABLE [dbo].[Bids] CHECK CONSTRAINT [FK_Bids_BidNames]
GO
ALTER TABLE [dbo].[Bids] WITH CHECK ADD CONSTRAINT [FK_Bids_Customers] FOREIGN KEY([CustomerID])
REFERENCES [dbo].[Customers] ([CustomerID])
GO
ALTER TABLE [dbo].[Bids] CHECK CONSTRAINT [FK_Bids_Customers]
GO
ALTER TABLE [dbo].[Bids] WITH CHECK ADD CONSTRAINT [FK_Bids_Items] FOREIGN KEY([ItemID])
REFERENCES [dbo].[Items] ([ItemID])
GO
ALTER TABLE [dbo].[Bids] CHECK CONSTRAINT [FK_Bids_Items]
GO
I took your table script, ran in my DB and dragged it into a dbml and it didn't generate as nullable (VS2010, VB.NET 4.0):
<Global.System.Data.Linq.Mapping.ColumnAttribute(
Storage:="_BidNameID", AutoSync:=AutoSync.OnInsert,
DbType:="Int NOT NULL IDENTITY", IsPrimaryKey:=True,
IsDbGenerated:=True)>
Public Property BidNameID() As Integer
Get
Return Me._BidNameID
End Get
Set(value As Integer)
If ((Me._BidNameID = value) _
= False) Then
Me.OnBidNameIDChanging(value)
Me.SendPropertyChanging()
Me._BidNameID = value
Me.SendPropertyChanged("BidNameID")
Me.OnBidNameIDChanged()
End If
End Set
End Property
Maybe try one or more of these?
drop/recreate the physical table
delete/recreate your DB connection in Server Explorer
delete/recreate the dbml
manually edit the designer file
create additional datacontext partial class and manually maintain that table/mapping
I don't necessarily understand why but when I alter the Bids table and make the BidNameID field NOT NULL, it fixes the problem with the BidName.BidNameID field. It now resolves to int rather than nullable.

LINQ query in EF - many to many and a cross join

A simple stored procedure that I want to handle with LINQ instead:
SELECT
CASE WHEN mg.MovieID IS NULL THEN 0 else 1 end as Selected ,
g.genreID, g.GenreName
FROM dbo.Genres g LEFT JOIN
(
SELECT MovieID, GenreID FROM [dbo].[MovieGenre] m
WHERE m.MovieID = #Movie
) MG
ON g.[GenreID] = mg.[GenreID]
ORDER BY g.GenreName
I think this should be simple and I think it would be a common requirement, yet I can't figure it out nor have I found a solution via searching the web.
The app is in WPF backed by an EF model. Since EF hides the join table I need LINQ syntax that can deal with the absence of the intermediary table.
Classic many-to-many with a simple join table: table 1:Movies, table 2: Genres, Join table: MovieGenres. In the UI the user selects a specfic movie. For that movie I want to bring back ALL the genres and a bool value indicating whether the genre has been assigned to the movie. Hours of attempting this in LINQ have failed me, so the solution is currently to have the stored procedure above generate the values for me. I won't always be abe to do this with a stored procedure and would love to see a LINQ solution.
Here's the actual SQL table structures
CREATE TABLE [dbo].[Genres](
[GenreID] [int] IDENTITY(1,1) NOT NULL,
[GenreName] [nvarchar](15) NOT NULL,
CONSTRAINT [PK_Genres] PRIMARY KEY CLUSTERED
(
[GenreID] ASC
)) ON [PRIMARY]
GO
CREATE TABLE [dbo].[Movies](
[MovieID] [int] IDENTITY(1,1) NOT NULL,
[MovieTitle] [nvarchar](50) NOT NULL,
CONSTRAINT [PK_Movies] PRIMARY KEY CLUSTERED
(
[MovieID] ASC
))
ON [PRIMARY]
GO
CREATE TABLE [dbo].[MovieGenre](
[MovieID] [int] NOT NULL,
[GenreID] [int] NOT NULL,
CONSTRAINT [PK_MovieGenre] PRIMARY KEY CLUSTERED
(
[MovieID] ASC,
[GenreID] ASC
)) ON [PRIMARY]
GO
ALTER TABLE [dbo].[MovieGenre] WITH CHECK ADD CONSTRAINT [FK_Genres] FOREIGN KEY([GenreID])
REFERENCES [dbo].[Genres] ([GenreID])
GO
ALTER TABLE [dbo].[MovieGenre] CHECK CONSTRAINT [FK_Genres]
GO
ALTER TABLE [dbo].[MovieGenre] WITH CHECK ADD CONSTRAINT [FK_Movies] FOREIGN KEY([MovieID])
REFERENCES [dbo].[Movies] ([MovieID])
GO
ALTER TABLE [dbo].[MovieGenre] CHECK CONSTRAINT [FK_Movies]
GO
This should do the trick.
use from and in with the navigation property for a join
DefaultIfEmpty to make it a left join
Using a ternary operator ? : for the case statement
Query:
var query = from g in context.Genres
from m in g.Movies.Where(x => x.MovieID == movieId)
.DefaultIfEmpty()
orderby g.GenreName
select new {
Selected = m == null ? 0 : 1,
g.genreID,
g.GenreName
};

Resources