Select values of a row into separate variables in SQL Server - sql

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

Related

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

Declared varchar in where condition

I want to pass declared variables to where.
For example I have a table #test:
ID Amount
1 100
2 50
3 20
4 40
5 150
I want to do something like that:
declare #id varchar(11) = '(1, 4, 5)'
select * from #test where IDNumber in #id
How can I do that?
Create a table valued user defined function as given below. There are many examples available online.
Convert comma separated list to Table valued function
this will be giving you good results and better approach, than dynamic sql code.
Once you have the function dbo.split(#string NVARCHAR(4000),',') then use them in the JOIN as given below.
declare #id varchar(11) = '1, 4, 5'
select t.* from #test as t
JOIN dbo.Split(#id,',') AS csv
ON t.id = csv.data;
Try the following-:
declare #id varchar(11) = '(1, 4)'
declare #sql nvarchar(max)
set #sql='select * from TABLE_NAME where id in '+ #id
EXEC sp_sqlexec #sql
SQL Server 2014
As stated in the comments you'd be better off using another datatype.
But if you really did want to do it like your example, you could use dynamic sql:
DECLARE #ids VARCHAR(32) = '1,4,5';
DECLARE #result TABLE (ID INT, Amount INT);
DECLARE #sql NVARCHAR(MAX) =
N' SELECT ID, Amount
FROM #test
WHERE ID IN (' + #ids + ');';
PRINT #sql;
INSERT #result
EXEC(#sql);
SELECT*
FROM #result;
The results are placed into a table variable if you need to use them again in your script, if not you can just EXEC the sql

SQL Assign value to local variable take from table

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

How to use SQL Variables inside a query ( SQL Server )?

I have written the following SQL Stored Procedure, and it keeps giving me the error at
#pid = SELECT MAX(... The whole procedure is:
Alter PROCEDURE insert_partyco
#pname varchar(200)
AS
BEGIN
DECLARE #pid varchar(200);
#pid = SELECT MAX(party_id)+1 FROM PARTY;
INSERT INTO party(party_id, name) VALUES(#pid, #pname)
SELECT SCOPE_IDENTITY() as PARTY_ID
END
GO
Can anyone please tell me what I'm doing wrong here?
Alter PROCEDURE insert_partyco
#pname varchar(200)
AS
BEGIN
DECLARE #pid varchar(200);
SELECT #pid = MAX(party_id)+1 FROM PARTY;
INSERT INTO party(party_id, name) VALUES(#pid, #pname)
SELECT SCOPE_IDENTITY() as PARTY_ID
END
This has an advantage over SET with SELECT in that you can select expressions in multiple variables in one statement:
SELECT #var1 = exp1, #var2 = expr2 ... etc
declare #total int
select #total = count(*) from news;
select * from news where newsid = #total+2
//**news** table name and **newsid** column name
You need to use SET.
Alter PROCEDURE insert_partyco
#pname varchar(200)
AS
BEGIN
DECLARE #pid varchar(200);
SET #pid = (SELECT MAX(party_id)+1 FROM PARTY);
INSERT INTO party(party_id, name) VALUES(#pid, #pname)
SELECT SCOPE_IDENTITY() as PARTY_ID
END
GO
Alternatively, in your case you could make party_id an autoincremented value, so you wouldn't need to query the table.

How to make table dynamic in sql

Does anyone know how to write a script in stored proc to run the table based on the variable (or will it possible to do so?)?
for example:
I have 3 tables name called customer, supplier, and support
when user input 1, then run table customer, 2 table supplier and 3 table support
declare #input int;
if #input =1
begin
declare #table varchar(50); set #table = 'customer'
end
if #input =2
begin
declare #table varchar(50); set #table = 'supplier '
end
if #input =3
begin
declare #table varchar(50); set #table = 'support'
end
select *
INTO ##test
from #table
IF it really is that simple, why not just repeat the Select?
if #input =1
begin
Select * INTO ##test From customer
end
if #input =2
begin
Select * INTO ##test From supplier
end
if #input =3
begin
Select * INTO ##test From support
end
yes you can do it by using dynamic sql "EXEC" or by "Sp_Executesql" command.
Example :
USE Northwind
GO
CREATE TABLE #MyTemp
( RowID int IDENTITY,
LastName varchar(20)
)
DECLARE #SQL nvarchar(250)
SET #SQL = 'INSERT INTO #MyTemp SELECT LastName FROM Employees;'
EXECUTE sp_executesql #SQL
Why do you want to do this? It seems like a bad idea at first glance.
Can you post what your stored procedure is doing and any relevant tables? I suspect that you may be able to either:
Modify your schema in such a way
that you would no longer to do
this
Create different stored procedures
to do what you want on each table instead of forcing it into one proc.
There are several issues that come up when you use dynamic SQL that you should be aware of. Here is a fairly comprehensive article on the pros and cons.