insert a field value into a table from c# Form application - sql-server

I want to Insert a DateTime variable into a table by " Insert into " , I mean by using from coding not wizard.
fro example I have a table which has a some field and one of them is Time_1 and I've write a procedure which its duty is filling Information to my table and in my procedure I've used from :
Insert into my_table
values
('#name','#last_Name',#ID,#Time)
but SQL show error when I enter 12:45:00 for #Time
so please tell me how to enter times into my filed .
Thanks in advance
create procedure Insert_List
#code int, #name nvarchar(20),#lastname nvarchar(40),#time1 datetime,#time2 datetime,
#time3 datetime,#price1 int,#price2 int, #B1 int , #V1 int , #M1 int
as
begin
insert into Employee
values
(#code,#name,#lastname,#time1,#time2,#time3,#price1,#price2,#B1,#V1,#M1)
end
//and I try to execute my procedure by these information
execute Insert_List 1,'Keyvan','Fardi',10:00:00,18:15:00,19:10:00,10,10,10,10
select * from employee
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near ':'.

Insert into my_table values ('#name','#last_Name',#ID,#Time)
Since you are using a parameterized SQL statement, do not enclose the parameters in quotes. Instead:
INSERT INTO my_table VALUES (#name, #last_Name, #ID, #Time);
If you are still getting an error, post the error message and all proc code.

Related

Stored Procedure of counting duplicate value with output variable in MSSQL

I want to create stored procedure of counting duplicate value
here is code with out stored procedure
select count(PID) from tblPerson
group by Gender
tblPerson is my table and PID my primary key.
and this is my code for stored procedure and I need output so I have used it.
create proc spcheckunique
#gender varchar(max),
#count int output
as
begin
SELECT #count=COUNT(PID)
from tblPerson group by #gender= Gender
end
and this throws me error
Msg 102, Level 15, State 1, Procedure spcheckunique, Line 547
Incorrect syntax near '='.
Help me to fix this..
I think you are almost there:
create proc spcheckunique
#gender varchar(max),
#count int output
as
begin
SELECT #count=COUNT(PID)
from tblPerson
where #gender = gender
group by Gender
end
Use WHERE Condition instead of Group BY
create proc spcheckunique
#gender varchar(max),
#count int output
as
begin
SELECT #count=COUNT(PID)
from tblPerson WHERE #gender= Gender
end
I think the issue is here:
group by #gender= Gender
Remove the piece #gender =, you only need GROUP BY Gender.

SQL Server Insert Null error in spite of providing not null values

I am trying to do an insert but it is giving an error stating that credits cannot be null but I am not providing null. Attached Screenshot
Code: Insert into [dbo].[Course] values (12,'Java',1,1,1);
Error: Msg 515, Level 16, State 2, Procedure trgAfterInsert, Line 31
Cannot insert the value NULL into column 'Credits', table 'DemoCollege.dbo.Course'; column does not allow nulls. INSERT fails.
The statement has been terminated.
Trigger:
Create trigger trgAfterInsert2 ON [dbo].[Course]
After Insert
AS
Declare #cid int;
Declare #cname nvarchar(50);
Select #cid = i.CourseID from inserted i;
Select #cname = i.Title from inserted i;
Insert into dbo.CourseTemp values (#cid, #cname);
Print 'After insert trigger fired';
GO
There's an insert trigger on the table & that's where the error is being generated from.
There must be some logic in that is converting the provided credit value to a null value somehow.
Just provide the columns where you want to insert the values.
Insert into [dbo].[Course](ColName1, ColName2, ColName3, ColName4, etc..) values (12,'Java',1,1,1);
Most probably you're missing a col in the middle

SQL Server 2012 error handling in stored procedure

ALTER PROCEDURE Ins2(#id INT,#name NVARCHAR(50))
AS
BEGIN
BEGIN try
INSERT INTO abc (id, name)
VALUES (#id, #name)
END try
BEGIN catch
INSERT INTO exception
VALUES (Error_number(),
Error_severity(),
Error_state(),
Error_procedure(),
Error_line(),
Error_message(),
Getdate())
SELECT *
FROM exception
END catch
END
ERROR:
Msg 8152, Level 16, State 13, Procedure ins2, Line 19
String or binary data would be truncated.
The statement has been terminated.
In above stored procedure id is the primary key in the abc table.. while running this I want to insert the error details in the error table (exception).. but I am getting the above error..
Error is just due to fields length. Data being inserted contain length more than field length.
Check length of fields in both "abc" and "exception" table.
Hope this will help you.
I suspect an error occurs in your catch block.
Could you confirm that length of all char columns is big enough to hold data you're trying to insert into exception table?
For example the column that should store error message might be smaller in size than error message is.
You might set it to VARCHAR(MAX).
The problem is at the lenght of the data you are interting into the table . #nume param is 50 chars long ( as it's nvarchar(50) ) and the name from the abc table is maybe? not set to nvarchar(50) or bigger or is in a different format.
If you can't modify the structure of the table I suggest you trim the Parameter.
Go to your abc table select it and click ALT+F1, look at the column name and check if it's varchar or nvarchar and it lenght.
ALTER PROCEDURE Ins2(#id INT,#name NVARCHAR(50))
AS
Declare #sName nvarchar( <insert the lenght of the column name from table abc> )
set #sName = (SUBSTRING(LTRIM(RTRIM(#name),0,49)
BEGIN
BEGIN try
INSERT INTO abc (id, name)
VALUES (#id, #sName )
END try
BEGIN catch
INSERT INTO exception
VALUES (Error_number(),
Error_severity(),
Error_state(),
Error_procedure(),
Error_line(),
Error_message(),
Getdate())
SELECT *
FROM exception
END catch
END
`Declare #sName nvarchar( <insert the lenght of the column name from table abc> )` <--- this declare an variable with the lenght equal to the one from the table abc
`set #sName = (SUBSTRING(LTRIM(RTRIM(#name),0,49)` <-- select the first 50 chars from the parameter
LTRIM(RTRIM(#name) <-- always use this if you don't want any black spaces on either sides of the string
Also there is the posibility to output an error if the paramter lenght is to much for the field name in table abc.

SQL Server- Insert results from dynamic query and variable into same row of a temporary table

How do you insert the results of a dynamic SQL server query and a variable into the same row of a temp table.
Here is the format of the temporary table (#temp)
create TABLE #temp (YEAR INT, ACC_AMOUNT Money, REJ_AMOUNT Money, OUT_AMOUNT Money,TOT_AMOUNT Money)
The Stored PROC is executed by
exec sp_executesql #pSQL
and will return values that should go into the columns ACC_AMOUNT, REJ_AMOUNT, OUT_AMOUNT.
14569849.11 696235.49 1353464.92 16619549.52
I want to insert a variable (#pACCU_YEAR) for the Year and the results of the SP and insert the dyanmic query in the same Row. This is wrong, but this will give you an idea of what I mean.
insert into #temp (YEAR)
values (#pACCU_YEAR)
insert into #temp (ACC_AMOUNT , REJ_AMOUNT, OUT_AMOUNT,TOT_AMOUNT)
exec sp_executesql #pSQL
This will result in
YEAR ACC_AMOUNT REJ_AMOUNT OUT_AMOUNT TOT_AMOUNT
2014 NULL NULL NULL NULL
NULL 14569849.11 696235.49 1353464.92 16619549.52
I would like:
YEAR ACC_AMOUNT REJ_AMOUNT OUT_AMOUNT TOT_AMOUNT
2014 14569849.11 696235.49 1353464.92 16619549.52
Select #Year [Year]
,Acc_Amount
,other fields....
FROM #Temp
In response to the question asked in your comment.
Use this after the #pSql is run. Leave the column Year out of the declaration.
Alternatively, after it runs just:
update #temp
SET [Year]=#Year
What's the code inside #pSQL? Why don't do the INSERT in your dynamic query itself like
declare #pSQL varchar(max);
set #pSQL = 'some sql command;
some_other_sql_command;
.......
insert into #temp (ACC_AMOUNT , REJ_AMOUNT, OUT_AMOUNT,TOT_AMOUNT)
select blah,blah1,blah2,blah3
from blah_table;';
exec sp_executesql #pSQL;
can you please show me an example of how to select a column that is a
variable not within the table?
use same SELECT statement like
select #var1 as some_name, #var2 as some_other_name
as some_name is optional. That's to give a meaningful name to the selected field.

Show Actual Query Plan causes error?

Curious if anyone has experienced this problem before and what the root cause is. The problem is that an error occurs when executed in SQL 2012 with Include Actual Query Plan turned on. It works in 2008 R2 either way (with or without plan) and works in 2012 without the Plan turned on. I discovered this when testing out functionality against partitioned views.
--Setup
USE master
go
DROP DATABASE Test
GO
CREATE DATABASE Test
GO
USE Test
GO
CREATE TABLE DD (pkID int IDENTITY(1,1), FullDate date);
INSERT INTO DD (FullDate) VALUES ('2013-01-01')
INSERT INTO DD (FullDate) VALUES ('2013-01-02')
INSERT INTO DD (FullDate) VALUES ('2013-01-03')
INSERT INTO DD (FullDate) VALUES ('2013-01-04')
INSERT INTO DD (FullDate) VALUES ('2013-01-05')
GO
CREATE TABLE DC (pkID int IDENTITY(1,1), Filter varchar(32), FilterGroup varchar(32));
INSERT INTO DC (Filter, FilterGroup) VALUES ('one', 'groupone')
INSERT INTO DC (Filter, FilterGroup) VALUES ('two', 'grouptwo')
INSERT INTO DC (Filter, FilterGroup) VALUES ('three', 'groupone')
GO
CREATE TABLE FDA1 (pkID int IDENTITY(1,1), fkpID int, fkCID int, fkDateID int)
INSERT INTO FDA1(fkpID, fkCID, fkDateID) VALUES (1,1,1)
INSERT INTO FDA1(fkpID, fkCID, fkDateID) VALUES (1,2,1)
INSERT INTO FDA1(fkpID, fkCID, fkDateID) VALUES (1,1,3)
INSERT INTO FDA1(fkpID, fkCID, fkDateID) VALUES (1,3,5)
GO
CREATE TABLE FDA2 (pkID int IDENTITY(1,1), fkpID int, fkCID int, fkDateID int)
INSERT INTO FDA2(fkpID, fkCID, fkDateID) VALUES (2,1,2)
INSERT INTO FDA2(fkpID, fkCID, fkDateID) VALUES (2,2,2)
INSERT INTO FDA2(fkpID, fkCID, fkDateID) VALUES (2,1,4)
INSERT INTO FDA2(fkpID, fkCID, fkDateID) VALUES (2,3,5)
GO
CREATE VIEW FDA
AS
SELECT pkID, fkpID, fkCID, fkDateID FROM FDA1
UNION ALL
SELECT pkID, fkpID, fkCID, fkDateID FROM FDA2
GO
CREATE FUNCTION GetFilter
(
#pID int
, #filterGroup varchar(32)
)
RETURNS #Filter TABLE
(
CID int
)
AS
BEGIN
INSERT INTO
#Filter
SELECT
dc.pkID
FROM
DC dc
WHERE
dc.FilterGroup = #filterGroup
RETURN
END
GO
CREATE PROC test (#ID int)
AS
BEGIN
BEGIN TRY
DECLARE #FilterGroup varchar(32) = 'groupone'
SELECT
CAST(MIN(dd.FullDate) As datetime) as ProjectReviewStartDate
FROM
dbo.FDA fda
INNER JOIN dbo.DD dd On fda.fkDateID = dd.pkID
INNER JOIN dbo.GetFilter(#ID, #FilterGroup) ctl on fda.fkCID = ctl.CID
WHERE
fda.pkID = #ID
OPTION (RECOMPILE);
RETURN 0;
END TRY
BEGIN CATCH
--Declare variables for error information.
Declare
#ErrorMessage nvarchar(max),
#ErrorSeverity bigint,
#ErrorState int;
--Populate error information.
Select
#ErrorMessage = ERROR_MESSAGE(),
#ErrorSeverity = ERROR_SEVERITY(),
#ErrorState = ERROR_STATE();
--Re-throw error to calling method.
RAISERROR(#ErrorMessage, #ErrorSeverity, #ErrorState);
--Failure
RETURN -1;
END CATCH;
END
GO
Now that setup is done, let's run the actual code, first "Include Actual Execution Plan"
USE Test
GO
SET STATISTICS IO ON;
SET STATISTICS TIME ON;
GO
DECLARE #id int = 1
DECLARE #tbl table (dt datetime)
DECLARE #findate datetime
INSERT #tbl EXEC test #id
SELECT #findate = dt FROM #tbl
SELECT #findate
GO
You should receive the result of: 2013-01-01 00:00:00.000.
Now turn on Include Actual Execution Plan and you will receive the result of NULL and see an error (In SQL 2012):
Msg 50000, Level 16, State 10, Procedure test, Line 33
String or binary data would be truncated.
With Include Actual Execution Plan on and removing the Try/Catch block from the proc removes the error and returns the correct result. However again this works fine in 2008R2.
Any ideas?
Thanks
I don't have an answer for you yet, just more ammo that you have likely encountered a bug.
First, to prove that this doesn't involve RAISERROR specifically, changing that line to:
THROW;
Returns this error message instead:
Msg 8152, Level 16, State 10, Procedure test, Line 7
String or binary data would be truncated.
So this shows that the error is happening in the SELECT call and has something to do with the combination of TRY/CATCH and show actual plan.
Next, let's see what the metadata describes as the output for the stored procedure:
SELECT name, system_type_name
FROM sys.dm_exec_describe_first_result_set_for_object
(OBJECT_ID('test'), NULL);
Results:
name system_type_name
---------------------- ----------------
ProjectReviewStartDate datetime
Now let's see what it says about the metadata (well, actually, turns out an error message) if we try to test the metadata for the batch you're running:
SELECT [error_message]
FROM sys.dm_exec_describe_first_result_set(N'DECLARE #id int = 1
DECLARE #tbl table (dt datetime)
DECLARE #findate datetime
INSERT #tbl
EXEC test #id', -1, NULL);
The result:
error_message
----------------------------------------------------------
Incorrect syntax near '-'.
The batch could not be analyzed because of compile errors.
There is no - in the batch. And this is with execution plan turned off. And you get the same result even if you comment out the insert in the batch above. Even for example:
SELECT error_message
FROM sys.dm_exec_describe_first_result_set(N'EXEC test 1', -1, NULL);
The error message changes ever so slightly (look closely):
error_message
----------------------------------------------------------
Incorrect syntax near '1'.
The batch could not be analyzed because of compile errors.
We've removed any involvement of showplan or potential truncation and we still can demonstrate that SQL Server has some kind of problem compiling and/or generating metadata for this simple batch.
Seems to be a pretty simple repro, and you have workarounds, but I would definitely file this on Connect.
edit
I see that you have filed a bug; anyone else who can repro this situation should vote and confirm repro:
http://connect.microsoft.com/SQLServer/feedback/details/785151/show-actual-query-plan-causes-error

Resources