Create a table and default column value to a received variable parameter - sql-server

I'm working on a MSSQL stored procedure.
I receive a table valued parameter (#accountPropsTVP) and a single variable (#accountID) from the C# server.
#accountPropsTVP has 2 columns:
valueTypeID int
value varchar(max)
Note: I'm never sure how many rows will be in this table.
#accountID is an int.
I need to merge everything received into one table, so that it ends up looking like so:
#temporaryTable:
#accountID (always the same for all rows)
valueTypeID
value
Below is what I have tried, but I get an error:
Msg 112, Level 15, State 4, Procedure insertAccountProps, Line 20
Variables are not allowed in the CREATE TABLE statement.
CREATE PROCEDURE insertAccountProps
-- Received parameters
#accountID int,
#accountPropsTVP accountPropsTVP READONLY
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
-- declare new table
DECLARE #accountPropsTemp TABLE
(
accountID int not null DEFAULT (#accountID),
valueTypeID int not null,
value varchar(max) not null
)
-- insert received TVP into new temp table, so that we can manipulate it (tvp's are read only :( )
INSERT INTO #accountPropsTemp
SELECT *
FROM #accountPropsTVP
-- select all from TVP and add it into temp table created above
INSERT INTO dbo.accountsProps
SELECT *
FROM #accountPropsTemp
END
GO
Maybe there's a simpler way of doing this?

Your issue is here:
DECLARE #accountPropsTemp TABLE
(
accountID int not null DEFAULT (#accountID),
valueTypeID int not null,
value varchar(max) not null
)
You're assigning a variable as a default value which as the error message clearly states is not allowed.
The best option for this is to change your syntax to:
DECLARE #accountPropsTemp TABLE
(
accountID int not null,
valueTypeID int not null,
value varchar(max) not null
)
INSERT INTO
#accountPropsTemp
SELECT
#AccountID
,ValueTypeID
,Value
FROM
#accountPropsTVP

Related

Compare two KeyValue types data in SQL Server 2012

I have the below data available in a table
DECLARE #AddressTbl As Table (ID int identity,Address varchar(100))
INSERT INTO #AddressTbl
VALUES ('State:AndhraPradesh,Dist:Prakasam')
Next time when I enter the same value I should be notified that this value exists in the table.
For this I will use an sp with warning message that the data is available. But I want how to implement the logic to compare the data.
Create Procedure usp_InsertAddress
(
#Address varchar(100)
)
AS
DECLARE #ID INT
SELECT #ID=(SELECT ID FROM #AddressTbl WHERE Address = #Address)
IF #ID IS NULL
BEGIN
INSERT INTO #AddressTbl
VALUES ('State:AndhraPradesh,Dist:Prakasam')
END;
I may enter the address like 'Dist:Prakasam,State:AndhraPradesh'
and there may be some blank spaces also. So need to parse the address and check the key and values.
I will use permanent table instead of table variable.
Appreciate your help.
You can use if exists for check. Or you can add unique CONSTRAINT in your table. The UNIQUE constraint ensures that all values in a column are different. This will return error if you are trying to insert duplicate value.
Create Procedure usp_InsertAddress
(
#Address varchar(100)
)
AS
if exists(SELECT ID FROM #AddressTbl WHERE Address = #Address)
begin
select 'Value is Already Exist in Table'---For Warning
end
else
BEGIN
INSERT INTO #AddressTbl
VALUES ('State:AndhraPradesh,Dist:Prakasam')
select 'Value Inserted Sucessful'---For Success
END;

SQL stored procedure - table as parameter

I have a database with different tables (all the same structure) where I'd like to run a stored procedure having a parameter that defines which table to query.
I can't seem to figure it out:
CREATE SCHEMA test;
GO
First I created a schema
CREATE TYPE DataType as TABLE (
[datetime] [datetime] NULL,
[testVar] [bigint] NULL)
GO
Then I created the table type
USE [TestDataFiles]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [test].[testing]
(
-- Add the parameters for the stored procedure here
#datetime datetime,
#t DataType READONLY
)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON
select top(10) *
from #t
where [datetime] > #datetime
END
GO
Then I created the stored procedure.
Exec test.testing #t = 'table.1', #datetime = '2017-01-01'
However when I call it I get the following error:
Msg 206, Level 16, State 2, Procedure test, Line 0 [Batch Start Line 0]
Operand type clash: varchar is incompatible with DataType
Same happens with:
Exec test.testing #t = [table.1], #datetime = '2017-01-01'
I have seen an example where in the procedure between the begin and select you put something like:
INSERT INTO table.1
( datetime, testVar)
But table.1 (or table.2 etc as I have a list of tables) has data and I don't want to change it.
Unless I'm meant to create a dummy table like I did the TYPE?
The examples I've found online havent been useful.
To do that you will need to use dynamic SQL
The basic procedure is to build up a string that will hold the statement you will execute, then execute it
declare #SQL nvarchar(1000)
declare #t as nvarchar (1000)
set #t = 'MyTable'
set #Sql = 'Select * from ' + #t
exec sp_executesql #sql
You have to pass parameter of type DataType. So, create variable of that type and pass it into stored procedure like
declare #table1 DataType
INSERT INTO #table1(datetime, testVar) values (..., ...)
Exec test.testing #datetime = '2017-01-01', #t = #table1

Prevent INSERT of NULL values for Stored Procedure

I'm working on a stored procedure that is supposed to update a table Order_TruckDelivery with info from another table Basket_TruckDelivery if the second table has any data. There are two columns in each of the tables: an int id and a datetime column called TruckDeliveryDate. If Basket_TruckDelivery has a date stored for the current basket id, then insert that date into the Order_TruckDelivery table.
Right now, the INSERT will execute regardless if there is anything in the Basket_TruckDelivery table, and this results in a NULL value for the TruckDelveryDate column in the Order_TruckDelivery column. I want to prevent this from happening but am not entirely sure how. Basically, I only want to perform and INSERT into the Order_TruckDelivery table IF the value of TruckDeliveryDate in Basket_TruckDelivery is NOT empty or null.
This is what I have so far...I have not done much work with stored procedures, so I am not sure what I've missed....
ALTER PROCEDURE [dbo].[SaveTruckIntoOrder]
#BasketID INT,
#OrderID INT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
DECLARE
#TruckDeliveryDate DATETIME
IF(EXISTS(SELECT uidBasket FROM [Basket_TruckDelivery] WHERE [uidBasket] = #BasketID))
BEGIN
SELECT
#TruckDeliveryDate = [TruckDeliveryDate]
FROM
[Basket_TruckDelivery]
WHERE
[uidBasket] = #BasketID
END
BEGIN
INSERT INTO [Order_TruckDelivery] ([uidOrder], [TruckDeliveryDate])
VALUES (#OrderID, #TruckDeliveryDate)
END
END
ALTER PROCEDURE [dbo].[SaveTruckIntoOrder] #BasketID INT
,#OrderID INT
AS
BEGIN
SET NOCOUNT ON;
DECLARE #TruckDeliveryDate DATETIME
IF (
EXISTS (
SELECT uidBasket
FROM [Basket_TruckDelivery]
WHERE [uidBasket] = #BasketID
)
)
BEGIN
SELECT #TruckDeliveryDate = [TruckDeliveryDate]
FROM [Basket_TruckDelivery]
WHERE [uidBasket] = #BasketID
END
IF (
#TruckDeliveryDate IS NOT NULL
AND #TruckDeliveryDate != ''
)
BEGIN
INSERT INTO [Order_TruckDelivery] (
[uidOrder]
,[TruckDeliveryDate]
)
VALUES (
#OrderID
,#TruckDeliveryDate
)
END
END

Can't insert a second row into a table though it insert first row by stored procedure

It inserted a first row successfully but it's not inserting any other row, though second row has no conflict of primary key
Code in my aspx.cs file:
outputParVal = sqlCmd.Parameters[outputParName].Value;
outparameter in stored procedure is--- "Result"
CREATE PROCEDURE [dbo].[RecruiterProfileInsert]
#CompanyId int,
#CompanyName varchar(200),
#EmailId varchar(50) ,
#Password varchar(20) ,
#ContactNumber varchar(15),
#Website varchar(50),
#CompanyProfile varchar(2000),
#IsVerified bit,
#Result Tinyint OutPut
--#CreatedDate datetime ,
--UpdatedDate datetime
AS
BEGIN
-- Insert statements for procedure here
--check whether #CompanyName already exist or not if exist then return
IF EXISTS(SELECT Top 1 * FROM RecruiterProfile WHERE #CompanyId = LTRIM(RTRIM(#CompanyId)))
BEGIN
SET #Result = 0-- Already Exists
END
ELSE
BEGIN
INSERT INTO RecruiterProfile
(
CompanyId,
CompanyName,
EmailId ,
Password ,
ContactNumber,
Website ,
CompanyProfile ,
IsVerified,
CreatedDate
)
VALUES
(
#CompanyId,
#CompanyName,
#EmailId ,
#Password,
#ContactNumber,
#Website,
#CompanyProfile,
#IsVerified,
GetDate()
)
set #Result =1
return
END
END
This is the problem:
SELECT Top 1 * FROM RecruiterProfile WHERE #CompanyId = LTRIM(RTRIM(#CompanyId))
This inherently makes no sense. You're comparing the variable to itself. Take the # sign out of one of the CompanyId references. The RTrim is unnecessary in SQL Server, and the LTrim doesn't make sense either because the later insert doesn't also LTrim so something is going to go wrong eventually.
Furthermore, inside of an EXISTS clause, TOP makes no sense unless you are using ORDER BY and doing something with the final result. Just do SELECT * inside of EXISTS clauses.
One more thing: if there is high concurrency and users could possibly try to insert the same thing at the same time, your query could still fail on a duplicate key violation.

T-SQL copying a table variable

I'm trying to make a copy of a table variable:
DECLARE #lt_Sections TABLE
(
teamId SMALLINT NOT NULL
)
DECLARE #lt_tempSections TABLE
(
teamId SMALLINT NOT NULL
)
-- populate some values in #lt_Sections
-- take a copy of #lt_Sections
SET #lt_tempSections = #lt_Sections
This is giving me an error:
Msg 137, Level 15, State 2, Line 14
Must declare the scalar variable "#lt_Sections".
What have I done wrong??
Thanks,
Mark
Set (or select) can be applied only to a scalar variable not a Table variable.
Instead of setting values you should use Insert
DECLARE #lt_Sections TABLE
(
teamId SMALLINT NOT NULL
)
DECLARE #lt_tempSections TABLE
(
teamId SMALLINT NOT NULL
)
insert #lt_TempSections(teamId)
select teamId from #lt_sections
You can't copy table variables like this (think of them more as you would a real/temporary table).
You'd need to:
INSERT #lt_tempSections (teamId)
SELECT teamId FROM #lt_Sections

Resources