I have a Transaction Inventory table that contains (TIID, TID, catid, itemid, quantity, price, isdelete, entryNumber) Columns. I inserted Tow record's and the TID is default null. When I execute update stored procedure I want to update all TID null column with id that i have where TIID IN(#TIID).
Table after record's inserted
Stored Procedure
ALTER procedure [dbo].[UpdateTIID]
#TIID nvarchar(max),
#TID nvarchar(50)
as
begin
declare #sql nvarchar(max)
set #sql='Update TransactionInventory Set TID='+ #TID +'
where TIID IN ('+ #TIID +') '
print #sql
exec (#sql)
end
C# Code
Related
This question already has answers here:
EF4 - The selected stored procedure returns no columns
(16 answers)
Closed 6 years ago.
I have a stored procedure which generate itself dynamically, in detail I am adding to where, order by clauses dynamically.
Here is my stored procedure:
ALTER PROCEDURE [dbo].[sp_GetConsultants]
#SearchQuery VARCHAR(MAX) = NULL,
#SortDataField VARCHAR(100),
#SortOrder VARCHAR(4),
#PageNum INT,
#PageSize INT,
#sql NVARCHAR(MAX) = NULL OUTPUT
AS
BEGIN
SET #sql = N'
WITH cte AS
(
SELECT
ID, [NO], Firstname, Lastname, ReferanceID,
CAST('''' AS VARCHAR(MAX)) AS ReferanceNO
FROM
dbo.Consultants
WHERE
ReferanceID IS NULL
UNION ALL
SELECT
c.ID, c.[NO], c.Firstname, c.Lastname, c.ReferanceID,
CASE
WHEN ct.ReferanceNO = ''''
THEN CAST(ct.[NO] AS VARCHAR(MAX))
ELSE CAST(ct.[NO] AS VARCHAR(MAX))
END
FROM
dbo.Consultants c
INNER JOIN
cte ct ON ct.ID = c.ReferanceID
)
SELECT *
FROM cte '
+ #SearchQuery
+ ' ORDER BY '
+ #SortDataField + ' ' + #SortOrder
+ ' OFFSET '+ CAST(#PageNum AS VARCHAR(20)) + ' ROW FETCH NEXT ' +CAST(#PageSize AS VARCHAR(20)) + ' ROWS ONLY'
EXEC sp_executesql #sql, N'#SearchQuery VARCHAR(MAX), #SortDataField VARCHAR(100), #SortOrder VARCHAR(4), #PageNum INT, #PageSize INT', #SearchQuery, #SortDataField, #SortOrder, #PageNum, #PageSize
END
I am trying to add this stored procedure to Entity Framework, but without success. Entity Framework can't create a complex type for my stored procedure, I click on the "Get Column Information" button, but the text box below says "The selected stored procedure returns no columns".
Do you know what is the problem?
P.S. It works if I remove parameters from #sql string
Probably because there is no proper SQL Statement in your procedure through which Entity Framework can detect the resulting columns.
A workaround is, to put a SQL Select statement at the end of the procedure which should tell Entity Framework about the result, for example just put following statement at the end of the procedure and update it
SELECT
CAST(1 AS int) AS ID
,CAST(1 AS int) AS [NO]
,N'Fist Name' AS Firstname
,N'Lasat Name' AS Lastname
,CAST(1 AS int) AS ReferanceID
,CAST('' AS VARCHAR(MAX)) AS ReferanceNO
After this, go in Entity Framework and import the procedure, it should show you the columns properly. Once you imported the SP in Entity Framework, go back in Procedure and comment out the last SELECT statement which we just added. This last statement is just for Entity Framework to understand what SP is going to return.
P.S. I don't know exactly the column types, so you should better change the column types in the select statement
I have a stored procedure with takes 2 parameters (StudentID and CurrentSmester) as input and return me table with fields :
Course Code
Update Type
Update Id
This stored procedure is created by another team in my office. I can not modify it but at the same point I want to use it in my Webservice (which I am building for android) to make sure data remains consistent.
My requirement is to get :
Course Code
Update Type
Update Id
Course Title
Can I create another store procedure which will call that store procedure with parameters as I mentioned, make a join with course table to get course title too.
Is this possible ? If yes can you please guide me through its implementation.
Thanking You and Happy New Year !!
Create a new stored procedure , insert the results coming back from your existing stored procedure into a temp table, join your Course table with that temp table and you are good to go ,
something like this.....
CREATE PROCEDURE usp_NewProc
#StudentID INT ,
#CurrentSmester INT
AS
BEGIN
SET NOCOUNT ON;
IF OBJECT_ID('tempdb..#temp', 'U') IS NOT NULL
DROP TABLE #temp
CREATE TABLE #temp
(
CourseCode [DataType],
UpdateType [DataType],
Update Id [DataType]
)
INSERT INTO #temp
EXEC existsting_proc #StudentID , #CurrentSmester
SELECT t.* , C.CourseTitle
FROM #temp t INNER JOIN CourseTable C on <join Condition>
IF OBJECT_ID('tempdb..#temp', 'U') IS NOT NULL
DROP TABLE #temp
END
You can insert the results from the STORED PROCEDURE into a temp table (table variable or temp table) and them select from that table and join onto the Courses table to retrieve the title.
SQL Fiddle DEMO
Example code
CREATE TABLE Courses(
CourseCode VARCHAR(50),
CourseName VARCHAR(250)
);
INSERT INTO Courses VALUES ('A','AA'), ('B','BB');
CREATE PROCEDURE OtherTeamsSP(
#StudentID INT,
#CurrentSmester INT
)
AS
SELECT 'A' CourseCode,
'FOO' UpdateType,
1 UpdateId;
CREATE PROCEDURE MyProcedure(
#StudentID INT,
#CurrentSmester INT
)
AS
CREATE TABLE #SPOutput(
CourseCode VARCHAR(50),
UpdateType VARCHAR(50),
UpdateId INT
)
INSERT INTO #SPOutput
EXEC OtherTeamsSP #StudentID, #CurrentSmester
SELECT *
FROM #SPOutput s INNER JOIN
Courses c ON s.CourseCode = c.CourseCode
DROP TABLE #SPOutput
Calling the new SP
EXEC MyProcedure 1,2
-- First Stored Procedure
CREATE PROCEDURE FirstSP
#MyFirstParam INT
AS
DECLARE #MyFirstParamValue INT
SELECT #MyFirstParamValue = #MyFirstParam * #MyFirstParam
RETURN (#MyFirstParamValue)
GO
-- Second Stored Procedure
CREATE PROCEDURE SecondSP
#SecondParam INT
AS
DECLARE #SecondParamValue INT
SELECT #SecondParamValue = #SecondParam * #SecondParam
RETURN (#SecondParamValue)
GO
-- Pass One Stored Procedure's Result as Another Stored Procedure's Parameter
DECLARE #FirstValue INT, #SeondValue INT
-- First SP
EXEC #FirstValue = FirstSP 5
-- Second SP
EXEC #SeondValue = SecondSP #FirstValue
SELECT #SeondValue SecondSP
GO
-- Clean up
DROP PROCEDURE FirstSP
DROP PROCEDURE SecondSP
GO
I am creating a web page to store data which is read from a Microsoft Excel worksheet.
I am passing the data to a stored procedure in SQL Server 2008.
Here is my C# code:
SqlConnection conn = new SqlConnection(AppDB);
conn.Open();
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "sp_ins_TaskDetails_from_Excel";
command.Parameters.AddWithValue("#TaskDetails", dtTaskDetailsFromExcel);
string sReturnValue = command.ExecuteNonQuery().ToString();
The stored procedure has one user defined table data type as parameter.
Here is my stored procedure:
ALTER PROCEDURE dbo.sp_ins_TaskDetails_from_Excel
(
#TaskDetails TypeInsertTaskFromExcel11 readonly
)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE
#ProjectID int,
#ProjectTeamID int,
#TeamLeaderUserID int,
#TaskCategoryName varchar(max),
#TaskDescription varchar(max),
#TeamMemberUserID int,
#TaskPriorityName varchar(10),
#PlanDuration float,
#PlanStartDate datetime,
#PlanEndDate datetime,
#TaskTypeName varchar(30),
#TaskStatusName varchar(30),
#TaskAllotName varchar(10),
#CreatedBy varchar(30),
#CreatedDate datetime,
#ISMailSend bit,
#Isvisible bit,
#UniqueID int
DECLARE TMSTaskDetailFromExcelCursor CURSOR FOR SELECT
ProjectID,
ProjectTeamID,
TeamLeaderUserID,
TaskCategoryName,
TaskDescription,
TeamMemberUserID,
TaskPriorityName,
PlanDuration,
PlanStartDate,
PlanEndDate,
TaskTypeName,
TaskStatusName,
TaskAllotName,
CreatedBy,
CreatedDate,
ISMailSend,
Isvisible,
UniqueID
FROM #TaskDetails
OPEN TMSTaskDetailFromExcelCursor
FETCH NEXT FROM TMSTaskDetailFromExcelCursor INTO
#ProjectID,
#ProjectTeamID,
#TeamLeaderUserID,
#TaskCategoryName,
#TaskDescription,
#TeamMemberUserID,
#TaskPriorityName,
#PlanDuration,
#PlanStartDate,
#PlanEndDate,
#TaskTypeName,
#TaskStatusName,
#TaskAllotName,
#CreatedBy,
#CreatedDate,
#ISMailSend,
#Isvisible,
#UniqueID;
WHILE ##FETCH_STATUS=0 BEGIN
-- Insert statements for procedure here
INSERT INTO ManageTasks (ProjectID, ProjectTeamID, TeamLeaderUserID,
TaskCategoryName,TaskDescription, TeamMemberUserID, TaskPriorityName,
PlanDuration, PlanStartDate, PlanEndDate, TaskTypeName,
TaskStatusName, TaskAllotName, CreatedBy, CreatedDate, ISMailSend, Isvisible,UniqueID)
VALUES (#ProjectID, #ProjectTeamID, #TeamLeaderUserID, #TaskCategoryName,
#TaskDescription, #TeamMemberUserID, #TaskPriorityName, #PlanDuration,
#PlanStartDate, #PlanEndDate, #TaskTypeName, #TaskStatusName,
#TaskAllotName, #CreatedBy, #CreatedDate, #ISMailSend,#Isvisible,#UniqueID);
FETCH NEXT FROM TMSTaskDetailFromExcelCursor INTO
#ProjectID,
#ProjectTeamID,
#TeamLeaderUserID,
#TaskCategoryName,
#TaskDescription,
#TeamMemberUserID,
#TaskPriorityName,
#PlanDuration,
#PlanStartDate,
#PlanEndDate,
#TaskTypeName,
#TaskStatusName,
#TaskAllotName,
#CreatedBy,
#CreatedDate,
#ISMailSend,
#Isvisible,
#UniqueID;
END;
CLOSE TMSTaskDetailFromExcelCursor;
DEALLOCATE TMSTaskDetailFromExcelCursor;
END
It receives the data and using a cursor in the same stored procedure each row will be inserted using an Insert statement in the same procedure.
While executing, all the data from Excel is passed to the stored procedure as exactly mentioned in the user defined table type.
But, the values are not stored in database and the stored procedure returns -1.
All the values are in correct format and order. I don't know what is going wrong.
Is there something I should change in the stored procedures?
There is a scenario where I have to drop primary key on a existing table and then insert a record into it. The table has a column called GUID as shown below
Create Table TEST_TABLE_VALUE (
TEST_TABLE_ID int Identity(1,1),
TEST_TABLE_VALUE int,
GUID uniqueidentifier Not Null Default newid(),
Primary Key (TEST_TABLE_ID, TEST_TABLE_VALUE)
)
Dropped the constraints using below code
Declare #TableName nvarchar(100)
Declare #TableId int
Declare #ConstraintName varchar(120)
Declare #IndexName varchar(120)
Declare #Command varchar(256)
Set #TableName = 'TEST_TABLE_VALUE'
Select #TableId = id From sysobjects Where [type]='U' and [name]=#TableName
Declare ConstraintDropCursor Cursor Local Fast_Forward
For Select name from sysobjects where (type='K' Or type='D' or type='F' or type='C') and parent_obj = #TableId
For Read Only
Open ConstraintDropCursor
Fetch Next From ConstraintDropCursor Into #ConstraintName
While ##Fetch_Status != -1
Begin
Set #Command = 'Alter Table dbo.' + #TableName + ' Drop Constraint ' + #ConstraintName
exec(#Command)
Fetch Next From ConstraintDropCursor Into #ConstraintName
End
Close ConstraintDropCursor
DeAllocate ConstraintDropCursor
After dropping the constraints when I tried to insert data into the table
Insert Into TEST_TABLE_VALUE (TEST_TABLE_VALUE) Values(1)
but got the below error:
Cannot insert the value NULL into column 'GUID', table 'CustApp1.dbo.TEST_TABLE_VALUE1'; column does not allow nulls. INSERT fails.
How can I solve this issue?
You have dropped the default for GUID column and it is not nullable column.Thus it is causing the issue. In case you want to insert lots of data and do not want constraint for maybe perf reasons. Then atleast do not drop the defaults for not nullable columns.
Well if you drop the default constraint you end up with
Create Table TEST_TABLE_VALUE (
TEST_TABLE_ID int Identity(1,1),
TEST_TABLE_VALUE int,
GUID uniqueidentifier Not Null,
Primary Key (TEST_TABLE_ID, TEST_TABLE_VALUE)
)
so if you wish to continue down this path you either have to provide a value for the GUID column
or also do
ALTER TABLE TEST_TABLE_VALUE ALTER COLUMN GUID uniqueidentifier NULL
to allow nulls.
i have creating a stored procedure to insert employee details.if this query is executed in form it will not return any value.
create PROCEDURE [dbo].[employee_mst_insertvalues]
#e_firstname varchar(100),
#e_middlename varchar(100),
#e_lastname varchar(100),
#e_address varchar(1000),
#e_phoneno varchar(15),
#mobileno varchar(15),
#UploadPhoto image
AS
declare #employee_id int
BEGIN
SET #employee_id=(select max(Employee_id) from mstEmployee)
if #employee_id is null
BEGIN
set #employee_id=1
END
else
BEGIN
set #employee_id=#employee_id+1
END
insert into mstEmployee (Employee_id,E_FirstName,E_MiddleName,E_LastName,E_Address,E_PhoneNo,E_MobileNo,UploadPhoto)
values(#employee_id,#e_firstname,#e_middlename,#e_lastname,#e_address,#e_phoneno,#mobileno,#UploadPhoto)
END
how can i return a integer value to check whether data is inserted or not.
SELECT ##ROWCOUNT will give you the number of rows affected by the insert statement.