My "data default (getdate())", it doesn't work - c#

I'm trying to insert in my SQL Server table the current date.
My table includes 3 files:
CREATE TABLE [dbo].[MyTable]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[Name] NVARCHAR (50) NOT NULL,
[Date] DATE
CONSTRAINT [DF_MyTable_Date] DEFAULT (getdate()) NOT NULL,
CONSTRAINT [PK_MyTable] PRIMARY KEY CLUSTERED ([Id] ASC)
)
When a new user wants to register in the system, he has only to insert his name.
In my table, the Id is generated automatically and the date too, but the date shows 01/01/0001 instead of the current day.
Where is the mistake?

if you create a datetime variable in C# like
var today_date = new DateTime();
and do a Console.WriteLine(today_date); u can see it print 0001-01-01
So this is default value of null..
Use DBNull.Value to insert a SQL NULL from C# and check the result

(Your_Date_Column) Make it Null / Not Null and give default value GetDate() but still it will not work. You have to create a trigger like this,
CREATE TRIGGER [dbo].[Trigger_Date] ON [dbo].[TableName] FOR INSERT AS BEGIN
Declare #Id int
set #Id = (select Id from inserted)
Update [dbo].[TableName]
Set Your_Date_Column = GetDate()
Where Id = #Id
END

Functions and triggers are not required. Just set a column with type Date or DateTime to NOT NULL DEFAULT CURRENT_TIMESTAMP.
Updated example code from the question:
CREATE TABLE [dbo].[MyTable]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[Name] NVARCHAR (50) NOT NULL,
[Date] DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
CONSTRAINT [PK_MyTable] PRIMARY KEY CLUSTERED ([Id] ASC)
)

Related

ASP.NET SQL elimininate duplicate Ids

I have two database tables for documenting a wound healing progression. Those are joined over the wound_id-Column like this:
So for one wound, I can create many progresses to show the healing of it. This is working fine.
Here is the code for the tables:
Table wound_details:
CREATE TABLE [dbo].[epadoc_mod_wound_details] (
[wound_id] INT IDENTITY (1, 1) NOT NULL,
[wound_type] VARCHAR (500) NULL,
[wound_description] VARCHAR (500) NULL,
[decuGrade] INT NULL,
[wound_comments] VARCHAR (500) NULL,
[wound_timeReal] DATETIME NULL,
[wound_timeGiven] DATETIME NULL,
[casenumber] INT NULL,
[username] VARCHAR (50) NULL,
[infectionstate] VARCHAR (50) NULL,
PRIMARY KEY CLUSTERED ([wound_id] ASC)
);
Table wound_progress:
CREATE TABLE [dbo].[epadoc_mod_wound_progress] (
[progress_id] INT IDENTITY (1, 1) NOT NULL,
[wound_length] INT NULL,
[wound_width] INT NULL,
[wound_depth] INT NULL,
[wound_surrounding] VARCHAR (500) NULL,
[wound_consistence] VARCHAR (500) NULL,
[wound_state] VARCHAR (200) NULL,
[wound_painscale] INT NULL,
[wound_itch] INT NULL,
[wound_id] INT NULL,
PRIMARY KEY CLUSTERED ([progress_id] ASC),
CONSTRAINT [FK_epadoc_mod_wound_progress_fk] FOREIGN KEY ([wound_id]) REFERENCES [dbo].[epadoc_mod_wound_details] ([wound_id]) ON DELETE CASCADE
);
Then I wrote a SELECT-Query to show all wounds for specific case number which are documented for the patient:
SELECT DISTINCT
dbo.epadoc_mod_wound_details.wound_id, dbo.epadoc_mod_wound_details.casenumber, dbo.epadoc_mod_wound_details.wound_type, dbo.epadoc_mod_wound_progress.progress_id, dbo.epadoc_mod_wound_details.wound_comments, dbo.epadoc_mod_wound_details.wound_timeReal, dbo.epadoc_mod_wound_details.username
FROM dbo.epadoc_mod_wound_details LEFT JOIN
dbo.epadoc_mod_wound_progress
ON dbo.epadoc_mod_wound_details.wound_id = dbo.epadoc_mod_wound_progress.wound_id
WHERE dbo.epadoc_mod_wound_details.casenumber = #casenr;
This is working fine though, but the problem is that ALL wound progresses are shown in the GridView, here is an example so you can see what I mean:
What I want to do is just show the latest progress of one wound, so for the above example just show the last entry with progressID 65:
33 65 1111111 Dekubitus
34 .. ....... .........
The SELECT DISTINCT approach didn't work and I also tried with MAX(progressID) but I always seem to get errors. I think I have to do something with ORDER BY or a second SELECT-Query before the JOIN.
Thanks for any advice!
You should use GROUP BY combined with MAX in your query.
SELECT
dbo.epadoc_mod_wound_details.wound_id,
dbo.epadoc_mod_wound_details.casenumber,
dbo.epadoc_mod_wound_details.wound_type,
MAX(dbo.epadoc_mod_wound_progress.progress_id) AS progress_id,
dbo.epadoc_mod_wound_details.wound_comments,
dbo.epadoc_mod_wound_details.wound_timeReal,
dbo.epadoc_mod_wound_details.username
FROM
dbo.epadoc_mod_wound_details
LEFT JOIN
dbo.epadoc_mod_wound_progress ON
dbo.epadoc_mod_wound_details.wound_id = dbo.epadoc_mod_wound_progress.wound_id
GROUP BY
dbo.epadoc_mod_wound_details.wound_id,
dbo.epadoc_mod_wound_details.casenumber,
dbo.epadoc_mod_wound_details.wound_type,
dbo.epadoc_mod_wound_details.wound_comments,
dbo.epadoc_mod_wound_details.wound_timeReal,
dbo.epadoc_mod_wound_details.username;
Since you only want the progress_id, The easies way to do it is using a correlated subquery:
SELECT wound_id,
casenumber,
wound_type,
(
SELECT TOP 1 progress_id
FROM dbo.epadoc_mod_wound_progress AS WP
WHERE WP.wound_id = WD.wound_id
ORDER BY progress_id
) As progress_id,
wound_comments,
wound_timeReal,
username
FROM dbo.epadoc_mod_wound_details As WD
WHERE casenumber = #casenr;
I understand you need each record of "epadoc_mod_wound_details" with the latest record of "epadoc_mod_wound_progress".
You can try this:
select wound.wound_id, wound.casenumber, wound.wound_type,
wound.wound_comments, wound.wound_timeReal, wound.username, MAX(progress_id)
from epadoc_mod_wound_details wound
left join epadoc_mod_wound_progress progress on wound.wound_id = progress.wound_id
where wound.casenumber = ''
group by wound.wound_id, wound.casenumber, wound.wound_type,
wound.wound_comments, wound.wound_timeReal, wound.username

How do I link 3 tables using foreign keys?

I have made a table named "reservations" which contains a customer id and a house id. I made tables for houses and customers as well. I have made a datagrid, which contains the reservations data, but I also want it to contain the customers surname and the house code.
My tables are (in SQL Server Express):
CREATE TABLE [dbo].[houses]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[Code] VARCHAR(50) NULL,
[Status] VARCHAR(50) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
CREATE TABLE [dbo].[customers]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[Forename] VARCHAR(50) NULL,
[Surname] VARCHAR(50) NULL,
[Email] VARCHAR(50) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
CREATE TABLE [dbo].[reservations]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[HouseId] INT NULL,
[CustomerId] INT NULL,
[StartDate] DATE NULL,
[EindDate] DATE NULL,
PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_HouseId]
FOREIGN KEY ([HouseId]) REFERENCES [houses]([Id]),
CONSTRAINT [FK_CustomerId]
FOREIGN KEY ([CustomerId]) REFERENCES [customers]([Id])
);
I already created all the tables, but I don't know how to link them properly. I want to get the data and put it in a datagrid.
To select all data from Reservations, customers' Surname and house code, you need to run query:
Select R.*, C.Surname, H.Code
From [dbo].[reservations] R
inner join [dbo].[customers] C on C.Id = R.CustomerId
inner join [dbo].[houses] H on H.Id = R.HouseId
Try this:
select r.*,c.surname,h.code from reservation r,customers c,houses h where
r.customer_id=c.customer_id and r.house_id=h.house_id

How to use sql defined functions as fields?

I am creating tables in Sql Management Studio 2012 using SQL. How do I make fields or columns with names that are already defined in Sql Server e.g User_ID, User_Name. I want to use them as fields in my tables.
Table definition from Duplicate Post:
create table Ticket(
Ticket_Id varchar(10) not null,
TicketType_Id varchar(3) not null,
Ticket_PurchaseDate DateTime null,
LottoDraw_Id int null,
User_Id int null,
Ticket_IsWinner bit null
Primary Key(Ticket_Id,TicketType_Id)
)
Warp the column name like in brackets [ ] ... such as
create table Ticket(
Ticket_Id varchar(10) not null,
TicketType_Id varchar(3) not null,
Ticket_PurchaseDate DateTime null,
LottoDraw_Id int null,
[User_Id] int null,
Ticket_IsWinner bit null
Primary Key(Ticket_Id,TicketType_Id)
)

How to get column definition from query result

I need a way to get column definition from query result. Right now I'm using SQL Server 2012.
Here is the example scenario, I have two tables which are Event and Attendant whose definitions are below :
CREATE TABLE [dbo].[Event] (
[Id] INT NOT NULL,
[Name] NVARCHAR (50) NULL,
[Description] NVARCHAR (50) NULL,
[StartDate] DATETIME NULL,
[EndDate] DATETIME NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
CREATE TABLE [dbo].[Attendant] (
[Id] INT NOT NULL,
[EventId] INT NOT NULL,
[Name] NVARCHAR (50) NULL,
[Company] NVARCHAR (50) NULL
PRIMARY KEY CLUSTERED ([Id] ASC)
);
And then I have query such as :
SELECT Event.Name as EventName, Attendant.Name as GuestName
FROM Event
INNER JOIN Attendant ON Event.Id = Attendant.EventId
How Can I get the column definition for above example query result? My objective is to generate poco class to represent each record of any query result using c#.
you can use sp_columns sproc to retrieve information about the column definition of a specified table ... like this:
exec sp_columns Attendant
Use sp_columns, it returns column information for the specified objects(tables).
Refer this link for details.
select * from information_schema.columns where table_name = '<tablename>'

LINQ to SQL Stored procedure Insert

Hi I have the following stored procedure:
create procedure dbo.AddNewUser
(
#uName nvarchar(20),
#pass nvarchar(20),
#fName nvarchar(20),
#lName nvarchar(20)
)
AS
insert into [Users] (Username, Password, Firstname, Lastname)
values (#uName, #pass, #fName, #lName)
This is the code for my table:
CREATE TABLE [dbo].[Users] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[Username] NCHAR (20) NOT NULL,
[Password] NCHAR (20) NOT NULL,
[Firstname] NCHAR (20) NOT NULL,
[Lastname] NCHAR (20) NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
My windows forms program currently has 4 textboxes and 1 button. I am trying to insert the text from the textboxes into my database. This is the code from my click event:
DatabaseConnectionDataContext dc = new DatabaseConnectionDataContext();
dc.AddNewUser(tbUsername.Text, tbPassword.Text, tbFirstname.Text, tbLastname.Text);
dc.SubmitChanges();
When I start the program, enter some data in the textboxes and click the button the data from the textboxes is inserted into the table, but when i start the program again and enter some data into the textboxes, the new data is inserted on the first line instead creating a new line and the old data is erased. Anyone can suggest why is this happening?
You are missing the check if user exists, normally you would do that by id.
using (var dc = new DatabaseConnectionDataContext()){
if (dc.Users.Any(o => o.Username== tbUsername.Text && o.Password == tbPassword.Text ...){
...
}else{dc.AddNewUser(tbUsername.Text, tbPassword.Text, tbFirstname.Text, tbLastname.Text);}
dc.SubmitChanges();
}
EDIT: Having read comment from StefanoGermani
Are you running in memory ravenDb by any chance?

Categories