I was wondering why my SQL code isn’t working properly on SQL Server while when I upload it on phpmyadmin it works perfectly. Is it some difference between those SQL’s? Is someone able to make this code working well on SQL Server? I’ve posted only part of database but with your help I’ll get done the rest.
create database Biblioteka; use Biblioteka; create table Autorzy ( ID_Autora int(5) Primary Key auto_increment, Imie varchar(25), Nazwisko varchar(25) ); create table Czytelnicy ( ID_Czytelnika int(3) Primary Key auto_increment, ID_Klasy int(3), Imie varchar(25), Nazwisko varchar(25), PESEL char(11) ); create table Klasa ( ID_Klasy int(3) Primary Key auto_increment, Nazwa_Klasy varchar(5) ); alter table Czytelnicy add foreign key (ID_Klasy) references Klasa(ID_Klasy); insert into Autorzy values('','Stefan','Batory'); insert into Autorzy values('','Gabriela','Zapolska'); insert into Autorzy values('','Joanne','Rowling'); insert into Czytelnicy values('','1','Adam','Nowak','97091309264'); insert into Czytelnicy values('','2','Anna','Kowalczyk','99062312546'); insert into Czytelnicy values('','2','Jan','Dabrowski','77022610926'); insert into Klasa values('','1A'); insert into Klasa values('','2B'); insert into Klasa values('','3C');
Advertisement
Answer
As a starter, your original MySQL code has issues:
inserting an empty string in an auto-incremented column is not supported; instead, you should not insert in that column, and let the database automatically assign a value to it (this requires explicitly listing the columns that you want to
insert
into, which is a best practice in SQL anyway)you need to
insert
in tableKlasa
first, then insert into referencing tableCzytelnicy
When it comes to translating this to SQL Server:
auto_increment
is not supported; you can useidentity(1, 1)
insteadthe
int
does not accept a length
This would work:
create table Autorzy( ID_Autora int identity(1, 1) Primary Key, Imie varchar(25), Nazwisko varchar(25) ); create table Czytelnicy( ID_Czytelnika int identity(1, 1) Primary Key, ID_Klasy int, Imie varchar(25), Nazwisko varchar(25), PESEL char(11) ); create table Klasa( ID_Klasy int identity(1, 1)Primary Key, Nazwa_Klasy varchar(5) ); alter table Czytelnicy add foreign key (ID_Klasy) references Klasa(ID_Klasy); insert into Autorzy(Imie, Nazwisko) values('Stefan','Batory'); insert into Autorzy(Imie, Nazwisko) values('Gabriela','Zapolska'); insert into Autorzy(Imie, Nazwisko) values('Joanne','Rowling'); insert into Klasa(Nazwa_Klasy) values('1A'); insert into Klasa(Nazwa_Klasy) values('2B'); insert into Klasa(Nazwa_Klasy) values('3C'); insert into Czytelnicy(ID_Klasy, Imie, Nazwisko, PESEL) values(1,'Adam','Nowak','97091309264'); insert into Czytelnicy(ID_Klasy, Imie, Nazwisko, PESEL) values(2,'Anna','Kowalczyk','99062312546'); insert into Czytelnicy(ID_Klasy, Imie, Nazwisko, PESEL) values(2,'Jan','Dabrowski','77022610926');