SQL Assign value to local variable take from table - sql

This i my procedure,that determines classId and liveareaId for Animal to insert it into table
CREATE PROCEDURE insertAnimal
#name nvarchar,
#birthyear int,
#classname nvarchar,
#livearea nvarchar
AS
BEGIN
DECLARE #classid int
DECLARE #liveareaid int
SET #classid =
(SELECT Id
FROM dbo.Class
WHERE dbo.Class.Name = #classname)
SET #liveareaid =
(SELECT Id
FROM dbo.LiveArea
WHERE Name = #livearea)
INSERT INTO dbo.Animal (Name,BirthYear,ClassId,LiveAreaId) VALUES
(
#name,
#birthyear,
#classid,
#liveareaid
)
END
GO
I have a error:
Cannot insert the value NULL into column 'ClassId', table 'ZOO.dbo.Animal'; column does not allow nulls. INSERT fails.
Why ClassId is null, can you tell me why whis doesn't work.
SET #classid =
(SELECT Id
FROM dbo.Class
WHERE dbo.Class.Name=#classname)

This is because you have declared #classname as only nvarchar and have not specified a length. When length is not specified in a nvarchar variable declaration statement, the default length is 1.
Declare as:
CREATE PROCEDURE insertAnimal
#name nvarchar(10),
#birthyear int,
#classname nvarchar(10),
#livearea nvarchar(10)
...

CREATE PROCEDURE insertAnimal
#name nvarchar,
#birthyear int,
#classname nvarchar,
#livearea nvarchar
AS
BEGIN
DECLARE #classid int
DECLARE #liveareaid int
SET #classid =
(SELECT Id
FROM dbo.Class
WHERE dbo.Class.Name=#classname
AND dbo.Class.Id IS NOT NULL)
SET #liveareaid =
(SELECT Id
FROM dbo.LiveArea
WHERE Name=#livearea)
INSERT INTO dbo.Animal (Name,BirthYear,ClassId,LiveAreaId) VALUES
(
#name,
#birthyear,
#classid,
#liveareaid
)
END
GO

Can you tell us which parameteres are passing by you while calling procedure in your page/Query as well as sample data in your database?
It looks like data does not exists in your database according to your parameters in page.
Make sure #classname and #liveareaid data you are passing as a parameter, must be in database table dbo.Class and dbo.LiveArea respectively.
Try below queries first in SQL server.Does it giving any output by same parameters?
SELECT Id FROM dbo.Class WHERE dbo.Class.Name = #classname
SELECT Id FROM dbo.LiveArea WHERE Name = #livearea

Related

Is it possible you instatiate a variable in SQL server using a select statement with another variable

I am attempting to DECLARE a variable then SET it's value using a secondary variable which has already had it's value set.
I have tried:
DECLARE #Type VARCHAR = 'Some unique text';
DECLARE #TypeId UNIQUEIDENTIFIER;
SET #TypeId =
(
SELECT Id
FROM Types
WHERE Name = #Type
)
select #TypeId
To no avail. The result of the final SELECT statement is null. The following works:
DECLARE #TypeId UNIQUEIDENTIFIER;
SET #TypeId =
(
SELECT Id
FROM Types
WHERE Name = 'Some unique text'
)
select #TypeId
but I have several tables linked via dependencies and to delete an entry I need to traverse the tables in the correct order pulling the correct Ids. It is likely I will need to do this frequently so I want to reduce the leg work and just enter the text once and the script do the rest.
Is the syntax wrong or is this not possible?
DECLARE #Type VARCHAR = 'Some unique text';
It seems like you try to configure the variable value to be 'Some unique text' but since the type of the variable is VARCHAR(1) then when you set the value the server implicitly CONVERT it to VARCHAR(1) which lead to trunctaing the string and using only the first character
DECLARE #Type VARCHAR = 'Some unique text';
SELECT #Type
GO -- result is "S" and not "Some unique text"
To clarify, using DECLARE #Type VARCHAR without explicitly set the length is translated into 'DECLARE #Type VARCHAR(1)'
As a result of this issue, your comparing of the value probably result with no rows since you compare "S" and not "Some unique text". Your sub query is the same as SELECT Id FROM Types WHERE Name = 'S'
Here is a simple illustration of the issue
------------ DDL+DML: Creating sample table with some data
DROP TABLE IF EXISTS t1, t2
GO
CREATE TABLE t1 (
ID int, [Name] NVARCHAR(100)
)
GO
INSERT t1 (ID, [Name]) Values
(1, 'Mobile '),
(2, 'TV '),
(3, 'Display')
GO
----------- Using VARCHAR without length returns nothing
DECLARE #Type VARCHAR = 'Mobile';
SELECT #Type
DECLARE #TypeId INT;
SET #TypeId =
(
SELECT Id FROM t1 WHERE Name = #Type
)
select #TypeId
----------- Using VARCHAR(100) works great
DECLARE #Type VARCHAR(100) = 'Mobile';
SELECT #Type
DECLARE #TypeId INT;
SET #TypeId =
(
SELECT Id FROM t1 WHERE Name = #Type
)
select #TypeId

How do I pass a parameter value from one stored procedure to another?

I'm trying to pass the input parameters from one stored procedure to another stored procedure, the value of the parameter will be used to be inserted into a table.
I have two stored procedures, here is the logic for the SP's:
First one -
CREATE PROCEDURE [abc].[SP1](
#ID1 INT
#ID2 INT
#Date VARCHAR(10)
#Value VARCHAR(50)
)
AS
Select into #temp...
EXEC [abc].[SP2] #ID1, #ID2, #Date, #Value
Select...
Second one -
CREATE PROCEDURE [abc].[sp2](
#bID1 INT
#bID2 INT
#bDate VARCHAR(10)
#Value VARCHAR(50)
)
DECLARE #bID1 INT, #bID2 INT, #bDate VARCHAR(10), #Value VARCHAR(50)
--main part that I'm concerned with, getting the parameter values to work
SELECT #bID1, #bID2, #bDate, #Value, x.col1, x.col2
INTO [abc].[tableA]
FROM tableX x
When I try this I receive an error saying that I, "must declare the scalar variable"
It's not how you create procedures in SQL Server. You should do something like this:
CREATE PROCEDURE [SP1]
#ID1 INT
,#ID2 INT
,#Date VARCHAR(10)
,#Value VARCHAR(50)
AS
Select into #temp...
Secondly, when you declared parameteres for the procedure you cannot declare variables with the same names below:
CREATE PROCEDURE [abc].[sp2]
#bID1 INT
,#bID2 INT
,#bDate VARCHAR(10)
,#Value VARCHAR(50)
AS
--main part that I'm concerned with, getting the parameter values to work
SELECT #bID1, #bID2, #bDate, #Value, x.col1, x.col2
INTO [abc].[tableA]
FROM tableX x

Select values of a row into separate variables in SQL Server

I have a table in SQL Server. The problem is how can I save the values of each column of a single row into separate variable in SQL Server 2012.
Something like:
SELECT Id, Name, School
FROM tblSchool
WHERE Id = 2
Then save the values of Id, Name, School into separate variables
If you want the values to be stored in separate variables (Your query returns only one matching row)
You can do like following
DECLARE #ID INT
DECLARE #Name VARCHAR(100)
DECLARE #School VARCHAR(100)
SELECT TOP 1 #ID=Id,#Name=Name,#School=School FROM tblSchool WHERE Id=2
SQL Server also supports table type variables, for your case you can create a table type as following.
CREATE TYPE [dbo].[MyVairable] AS TABLE(
Id INT NOT NULL,
Name VARCHAR(100) NULL,
School VARCHAR(100)
)
Declare the variable as following.
DECLARE #MyVariable [dbo].[MyVairable]
To select the rows into your variable.
INSERT INTO #MyVariable
SELECT Id,Name,School FROM tblSchool WHERE Id=2
Simply Declare the variables and stored it using:
DECLARE #ID INT, #Name VARCHAR(50), #School VARCHAR(50)
SELECT #ID=Id,#Name=Name,#School=School FROM tblSchool WHERE Id=2
DECLARE #ID INT
DECLARE #Name VARCHAR(50)
DECLARE #School VARCHAR(50)
SELECT #ID=Id,#Name=Name,#School=School
FROM tblSchool
WHERE Id=2

Stored procedured doesnt give the result back

I have written such a stored procedure, it must return a result, but it doesnt do that. it returns only a message that stored procedure runs successfully.
How should I change my SP?
CREATE PROCEDURE TestTVP
(
#param1 int,
#param2 int,
#a int OUTPUT
)
as
SET NOCOUNT ON
DECLARE #T1 as TABLE
(
PK INT IDENTITY NOT NULL,
Wert INTEGER,
Name INTEGER
)
INSERT INTO #T1(Wert,Name) VALUES (#param1,#param2)
return select count(*) from #T1
GO
exec TestTVP '1','22'
you have to pass OUTPUT parameter
declare #z int
exec TestTVP '1','22' ,#z output
and remove return from Stored Procedure make it only
...
select count(*) from #T1
You can use out parameter if you want the output :
DECLARE #Z int
EXEC TestTVP '2', '22',#z out

Working with IF/ELSE and inserting into temp tables

I'm trying to write a SQL query that accepts two inputs (a content ID and a content type), populates a temp table from different source tables depending on what the user sets as content type, and then finally runs a query against the temp table. I think I'm getting stuck on incorporating my temp table into my IF/ELSE statements.
So my question is, why does this return some non-zero number of results:
DECLARE #contentID int, #contenttype varchar
SET #contentid = 28861
SET #contenttype = 'resource'
DECLARE #tags_current TABLE (contentID int, taxonomyID int, isPrimary int)
INSERT INTO #tags_current (contentID, taxonomyID, isPrimary)
SELECT resourceID as contentID, taxonomyID, isPrimary
FROM resource2taxonomy r2t
WHERE r2t.resourceID = #contentID
SELECT * FROM #tags_current
Whereas this returns zero results:
DECLARE #contentID int, #contenttype varchar
SET #contentid = 28861
SET #contenttype = 'resource'
DECLARE #tags_current TABLE (contentID int, taxonomyID int, isPrimary int)
IF (#contenttype = 'resource')
BEGIN
INSERT INTO #tags_current (contentID, taxonomyID, isPrimary)
SELECT resourceID as contentID, taxonomyID, isPrimary
FROM resource2taxonomy r2t
WHERE r2t.resourceID = #contentID
END
SELECT * FROM #tags_current
Also, I've tried this, and it also returns zero results:
DECLARE #contentID int, #contenttype varchar, #command varchar
SET #contentid = 28861
SET #contenttype = 'resource'
DECLARE #tags_current TABLE (contentID int, taxonomyID int, isPrimary int)
IF (#contenttype = 'resource')
BEGIN
SET #command = 'INTO #tags_current (contentID, taxonomyID, isPrimary) SELECT resourceID as contentID, taxonomyID, isPrimary FROM resource2taxonomy r2t WHERE r2t.resourceID = #contentID'
END
EXECUTE(#command)
SELECT * FROM #tags_current
I've read up on this, this, and this, but for some reason it's just not clicking for me. I'm using MS SQL Server 2014, in case that helps. Here's the SQL Fiddle. Thanks!
This is actually very simple, you aren't giving a length to #contenttype, as such, by default it's taking a length of 1 char.
This will be clear if you do this:
DECLARE #contentID int, #contenttype varchar
SET #contentid = 28861
SET #contenttype = 'resource'
SELECT #contenttype
The result is r, so, IF (#contenttype = 'resource') is not true