Can I insert into a temp table the result of a stored procedure plus another value? - sql

I have a temp table that needs the values of a Stored procedure. So the SP inserts 3 columns into the temp table, then I want to add a datetime to every row without modifying the SP.
Since I call the SP 3 times, each time with a different datetime, I can't just update the whole temp table.
Any Suggestions?
DECLARE #temp TABLE
(
id INT IDENTITY(1,1),
Name VARCHAR(150),
Address VARCHAR(25),
Date DATETIME
)
WHILE (#count>=#daysBack)
BEGIN
SET #date=DATEADD(dd, #count, GETDATE())
INSERT INTO #temp (Name,Address)
EXEC[dbo].StoredProc#date
--I Want to check for Null and insert the date there
Update #temp SET Date=#date WHERE Date=''
SET #count=#count-1

Yes. Create the temp table and in the added date column that does not have representation from your sproc put a default value constraint of getdate() or whatever date formula you need. In the insert statement specify the columns explicitly and omit the date column and it should work. As the rows are added the default value constraint will kick in and fill that column for you.
example:
create table #tmp (c1 int, c2 int, dt datetime default(getdate()) )
insert into #tmp
(c1, c2)
exec mysproc

Related

Insert data from one table to another table while the target table has a primary key

In SQL Server I have a table as RawTable (temp) which gets fed by a CVS, let's say it has 22 columns in it. Then, I need to copy existing records (ONLY FEW COLUMNs NOT ALL) into another table as Visitors which is not temporary table.
Visitor table has an ID column as INT and that is primary key and incremental.
RawData table
id PK, int not null
VisitorDate Varchar(10)
VisitorTime Varchar(11)
Visitors table
VisitorID, PK, big int, not null
VisitorDate, Varchar(10), null
VisitorTime Varchar(11), null
So I did:
insert into [dbo].[Visitors] ( [VisitorDate], [VisitorTime])
select [VisitorDate], [VisitorTime]
from RawTable /*this is temp table */
Seems SQL Server doesn't like this method so it throws
Msg 515, Level 16, State 2, Line 1
Cannot insert the value NULL into column 'VisitorID', table 'TS.dbo.Visitors'; column does not allow nulls. INSERT fails. The statement has been terminated.
How can I keep Sql Server not to complain about the primary key? this column as you know better will be fed by sql server itself.
Any idea?
Just because your visitors table has an ID column that is the primary key doesn't mean that the server will supply your ID values for you. if you want SQL to provide the ID's then you need to alter the table definition and make the visitorsId column an IDENTITY column.
Otherwise, you can psuedo-create these id's during the insert with the ROW_NUMBER function -
DECLARE #maxId INT;
SELECT #maxId = (SELECT MAX(visitorsId) FROM dbo.visitors);
INSERT INTO [dbo].[Visitors] ( [visitorsId],[VisitorDate], [VisitorTime])
SELECT #maxId + ROW_NUMBER() OVER (ORDER BY visitorDate), [VisitorDate], [VisitorTime]
from RawTable /*this is temp table */

sql current date constraint

I need to add a constraint to one table in my database. The table name is Experience. And there is a column named ToDate. Every time the select statement executes like following.
select ToDate from Experience
It should return current date.
So every time select statement executes, the ToDate column get updated with current date.
I know I can do this with some type of sql trigger but is there a way to do it by sql constraint.
like
alter table add constraint...
Any help will be appreciated.
Thanks
You can use a computed column. That's specified like colname as <expression>:
create table t1(id int, dt as getdate());
insert t1 values (1);
select * from t1;
To add contraint ...
create table tbl (id int identity, dt datetime, colval varchar(10))
ALTER TABLE dbo.tbl
ADD CONSTRAINT col_dt_def
DEFAULT GETDATE() FOR dt;
Example of inserting to the table ..
insert into dbo.tbl(colval)
select 'somevalue'
select * from dbo.tbl
The result will be ..
id dt colval
1 2014-08-19 13:31:57.577 somevalue
You cannot use a constraint, because a constraint is basically a rule on what can go in the table, how the table can relate to others, etc. It has no bearing on the data in the table once it goes into the table. Now if I am understanding you correctly, you want to update the ToDate column whenever you select that column. Now you can't use a trigger either as mentioned here and here. They suggest a stored procedure where you would use an update followed by an insert. This is probably my preferred SQL method to go with if you have to use it repeated, which you seem to have to do. Though Andomar's answer is probably better.
Try this link code make help full
http://www.sqlatoms.com/queries/how-to-use-the-getdate-function-in-sql-server-3/
CREATE TABLE ProductOrders
(
OrderId int NOT NULL PRIMARY KEY IDENTITY,
ProductName nvarchar(50) NOT NULL,
OrderDate datetime NOT NULL DEFAULT GETDATE()
)

Trigger to update another table WITH auto-increment value

I'm having trouble creating a trigger for my database.
I Have two tables, lets call them A and AHistory.
A has an ID and a value.
I want AHistory to keep track of the value and date for a set time.
AHistory Has an Auto Incremented ID, the value and a timestamp.
this is as far as I have gotten:
CREATE TRIGGER Atrigger
ON A
AFTER INSERT
AS
BEGIN
INSERT INTO AHistory
SELECT value FROM INSERTED
END
GO
Assuming that your db schema looks like
CREATE TABLE a
(id int identity primary key,
value varchar(32));
CREATE TABLE ahistory
(id int identity primary key,
aid int, value varchar(32),
eventdate datetime);
Your trigger might look like
CREATE TRIGGER atrigger ON A
AFTER INSERT AS
INSERT INTO ahistory (aid, value, eventdate)
SELECT id, value, GETDATE() FROM INSERTED;
Here is SQLFddle demo

Finding what value was inserted into an auto-incrementing field

I have two tables:
Rooms:
ID (auto-incrementing primary key, int)
Topic (varchar(50))
MangerId (varchar(50))
Rooms_Users:
UserId (varchar(50))
RoomId (varchar(50))
both fields together are the primary key
I want to insert a room but I also must insert the manger to the table rooms_users.
Here is what I have so far:
ALTER PROCEDURE [dbo].[Creat_Room] #MangerId varchar(50) ,#Topic varchar(50)
AS
BEGIN
SET NOCOUNT
insert into Rooms(ManagerId,Topic) values(#MangerId,#Topic)
insert into Rooms_Users(UserId,RoomId) values(#MangerId,?????????????)
END
The ????????????? is the problem: I don't know what to put here i want to put the roomid i insert above.
You can use the output clause. Look at MSDN here: OUTPUT Clause (Transact-SQL)
Example:
declare #tbl table
(
NewID int
)
insert into Rooms(ManagerId,Topic)
output inserted.ID into #tbl
values(#MangerId,#Topic)
Then the table variable will contains the new id given to the row you inserted
Use the SCOPE_IDENTITY() function:
ALTER PROCEDURE [dbo].[Create_Room]
#ManagerId varchar(50),
#Topic varchar(50)
AS
BEGIN
DECLARE #NewRoomID INT
insert into Rooms(ManagerId, Topic) values(#MangerId, #Topic)
SELECT #NewRoomID = SCOPE_IDENTITY()
insert into Rooms_Users(UserId, RoomId) values(#ManagerId, #NewRoomID)
END
This function will return the last inserted IDENTITY value in this particular scope - the scope of your stored procedure.

SQL INSERT stored procedure not working

Create Proc CrearNuevoAnuncio
#Titulo varchar(250),
#Precio int,
#Descripcion varchar(250),
#IDCategoria int,
#IDImagen int,
#Login varchar(200)
AS
INSERT INTO Anuncio VALUES(
#Titulo,
#Precio,
#Descripcion,
#IDCategoria,
#IDImagen,
#Login
)
The error is because the table anuncio has 1 more attribute: "idAnuncio". It's the primary key, and it's the indentity (autoincrement).
So, how can I handle this is the missing thing is an Identity. I don't want to pass that parameter from my front-end.
You need to specify the explicit list of columns in your insert statement:
INSERT INTO
Anuncio(Titulo, Precio, Descripcion, IDCategoria, IDImagen, Login)
VALUES
(#Titulo, #Precio, #Descripcion, #IDCategoria, #IDImagen, #Login)
Otherwise, SQL Server will try to insert values for ALL columns which fails here. It cannot insert a value into an IDENTITY column - that column will be set automatically by SQL Server upon inserting a new row, and is guaranteed to be unique.
Is the ID field of type "INT IDENTITY" ? In that case, you could access the value of the newly inserted ID like this:
DECLARE #NewID INT
SET #NewID = SCOPE_IDENTITY()
and possibly return it from the stored proc:
RETURN #NewID
Marc
You need to specify which value goes to which field.
INSERT INTO Anuncio (field1, field2, ...) VALUES (#Titulo, ...)