Placing column values in variables using single SQL query - sql

In SQL server, how can I place the value of more than one column in variables using one query?
Ex: my query is:
SELECT ET.ID,ET.Description,ET.DefaultTemplateText
FROM TBL_EMAILTEMPLATE ET
WHERE ET.NAME='OneWeekReminder'
I want to place the column values in variables.

You can use the following syntax:
Declare #id INT
Declare #desc VarChar(100)
Declare #template VarChar(100)
SELECT #id = ET.ID, #desc = ET.Description, #template = ET.DefaultTemplateText
FROM TBL_EMAILTEMPLATE ET
WHERE ET.NAME='OneWeekReminder'

declare the variables first then set them in the select clause.
declare
#ID int,
#Description varchar(10),
#DefaultTemplateText varchar(10)
select
#ID = ET.ID,
#Description = ET.Description,
#DefaultTemplateText = ET.DefaultTemplateText
from
TBL_EMAILTEMPLATE ET
where
ET.NAME = 'OneWeekReminder'

You can separate multiple assignments with a comma. For example:
declare #a varchar(50)
declare #b varchar(50)
select
#a = et.Description
, #b = et.DefaultTemplateText
from YourTable

Assuming only one row,
SELECT #id = ET.ID, #Description = ET.Description, #DefaultTemplateText = ET.DefaultTemplateText
FROM TBL_EMAILTEMPLATE ET
WHERE ET.NAME='OneWeekReminder'

Related

Must declare the scalar variable "#tabvar"

declare #departmentid int;
set #departmentid = 1;
declare #tabvar table (id int, name nvarchar(100))
begin
insert into #tabvar
select DepartmentID, Name
from HumanResources.Department where DepartmentID = #departmentid;
print #tabvar
end
It shows
Must declare the scalar variable "#tabvar".
The problem is
print #tabvar.id
Remove this and the code will work.
The following is equivalent functionality:
print #departmentid;

how to set two Variable with one select in sql

i have two Variable type in t-sql and want set they in sql. i use this code:
DECLARE #Id int
DECLARE #Name nvarchar(100)
set #Id, #Name = (Select Id, Name From Member Where username = #username)
but this not working, and i not want use this code:
set #Id = (Select Id From Member Where username = #username)
set #Name = (Select Name From Member Where username = #username)
i have use one select.
Here's the right syntax for what you want to do:
DECLARE #Id int
DECLARE #Name nvarchar(100)
SELECT #Id = Id, #Name = Name
From Member
Where username = #username

SQL Server: How to achieve re-usability yet flexibility in TSQL

I am using SQL Server 2008 R2. I am having some problems finding an effective coding pattern for SQL which supports code re-usability as well as flexibility. By re-usability, what I mean is keeping SQL queries in Stored Procedures and User Defined Functions.
Now, if I choose Stored Procedures, I will be sacrificing its usability in a query directly. If I choose User Defined Functions, I won't be able to use DML statements.
For example, suppose I created a Stored Procedures which inserts one contact record. Now, if I am having a table which can act as a source of multiple contact records, all I am left with are either WHILE loops or CURSORs, which is clearly not a recommended option, due to its performance drawbacks. And due to the fact that DML statements are not allowed in User Defined Functions, I simply cannot use them for this purpose.
Although, If I am not concerned with code re-usability, then instead of using Stored Procedures I can surely use same set of queries again and again to avoid while loops.
What pattern should I follow?
Here is a similar Stored Procedures:-
ALTER Proc [dbo].[InsertTranslationForCategory]
(
#str nvarchar(max),
#EventId int,
#CategoryName NVarchar(500),
#LanguageId int,
#DBCmdResponseCode Int Output,
#KeyIds nvarchar(max) Output
)as
BEGIN
DECLARE #XmlData XML
DECLARE #SystemCategoryId Int
DECLARE #CategoryId Int
Declare #Counter int=1
Declare #tempCount Int
Declare #IsExists int
Declare #TranslationToUpdate NVarchar(500)
Declare #EventName Varchar(200)
declare #Locale nvarchar(10)
declare #Code nvarchar(50)
declare #KeyName nvarchar(200)
declare #KeyValue nvarchar(500)
select #Locale=locale from languages where languageid = #LanguageId
SET #DBCmdResponseCode = 0
SET #KeyIds = ''
select #EventName = eventName from eventLanguages
where eventID = #EventId
--BEGIN TRY
Select #SystemCategoryId=CategoryId from SystemCategories where Name=rtrim(ltrim(#CategoryName))
Select #CategoryId=CategoryId from Categories where Name=rtrim(ltrim(#CategoryName)) and EventId=#EventId
if (#str='deactivate')
Begin
Delete from Codetranslation where CategoryId=#CategoryId
Update Categories set [Status]=0, Isfilter=0 where CategoryId=#CategoryId and Eventid=#EventId
Set #DBCmdResponseCode=2
return
End
set #XmlData=cast(#str as xml)
DECLARE #temp TABLE
(
Id int IDENTITY(1,1),
Code varchar(100),
Translation varchar(500),
CategoryId int
)
Insert into #temp (Code,Translation,CategoryId)
SELECT
tab.col.value('#Code', 'varchar(200)'),
tab.col.value('#Translation', 'varchar(500)'),#SystemCategoryId
FROM #XmlData.nodes('/Data') AS tab (col)
select #tempCount=Count(*) from #temp
if(IsNull(#CategoryId,0)>0)
Begin
While (#Counter <= #tempCount)
Begin
Select #IsExists= count(sc.categoryid) from #temp t Inner Join SystemCodetranslation sc
On sc.categoryid=t.CategoryId
where ltrim(rtrim(sc.code))=ltrim(rtrim(t.code)) and ltrim(rtrim(sc.ShortTranslation))=ltrim(rtrim(t.Translation))
and t.Id= #Counter
print #IsExists
Select #Code = Code , #KeyValue = Translation from #temp where id=#counter
set #KeyName = ltrim(rtrim(#EventName)) + '_' + ltrim(rtrim(#CategoryName)) + '_' + ltrim(rtrim(#Code)) + '_LT'
exec dbo.AddUpdateKeyValue #EventId,#Locale, #KeyName,#KeyValue,NULL,12
select #KeyIds = #KeyIds + convert(varchar(50),keyvalueId) + ',' from dbo.KeyValues
where eventid = #EventId and keyname = #KeyName and locale = #Locale
set #KeyName = ''
set #KeyValue = ''
Set #Counter= #Counter + 1
Set #IsExists=0
End
End
--- Inser data in Codetranslation table
if(isnull(#CategoryId,0)>0)
Begin
print #CategoryId
Delete from codetranslation where categoryid=#CategoryId
Insert into codetranslation (CategoryId,Code,LanguageId,ShortTranslation,LongTranslation,SortOrder)
SELECT
#CategoryId,
tab.col.value('#Code', 'varchar(200)'), #LanguageId,
tab.col.value('#Translation', 'varchar(500)'),
tab.col.value('#Translation', 'varchar(500)'),0
FROM #XmlData.nodes('/Data') AS tab (col)
Update Categories set [Status]=1 where CategoryId=#CategoryId and Eventid=#EventId
End
Set #DBCmdResponseCode=1
set #KeyIds = left(#KeyIds,len(#KeyIds)-1)
END
You can use table variable parameter for your user defined functions.
following code is an example of using table variable parameter in stored procedure.
CREATE TYPE IdList AS TABLE (Id INT)
CREATE PROCEDURE test
#Ids dbo.IdList READONLY
AS
Select *
From YourTable
Where YourTable.Id in (Select Id From #Ids)
End
GO
In order to execute your stored procedure use following format:
Declare #Ids dbo.IdList
Insert into #Ids(Id) values(1),(2),(3)
Execute dbo.test #Ids
Edit
In order to return Inserted Id, I don't use from Table Variable Parameter. I use following query sample for this purpose.
--CREATE TYPE NameList AS TABLE (Name NVarChar(100))
CREATE PROCEDURE test
#Names dbo.NameList READONLY
AS
Declare #T Table(Id Int)
Insert Into YourTable (Name)
OUTPUT Inserted.Id Into #T
Select Name
From #Names
Select * From #T
End
GO

Can SQL use calculate values as alias names

I am trying to find out how to use a calculated value as part of an alias name .
For example:
Select employeeName as ''name of guy' but where 'name of guy' could be getdate() + 'name o guy'
Addin qualifiers just prevents the code inside from calculating.
Is this possible in any way? I'm going to use a partition to group results by year and I need the column aliases to be based on the year thy are in
I don't know if it's what you are looking for but it could be a good starting :
DECLARE #var table(rownum int, rowkey varchar(60), ALIAS varchar(80))
INSERT INTO #var SELECT row_number() over (ORDER BY employeeName), employeeName, cast(getdate() AS varchar(12))+employeeName FROM Table1
DECLARE #query varchar(500)
DECLARE #rowkey varchar(60), #i int, #max int
SET #i = 1
SET #max = (SELECT count(*) FROM #var)
SET #query = ''
WHILE #i <= #max
BEGIN
SET #rowkey = (SELECT rowkey FROM #var WHERE rownum = #i)
SET #query = 'select employeeName as "'+(SELECT ALIAS FROM #var WHERE rowkey = #rowkey)+'" from Table1 where employeeName = '''+#rowkey+''';'
exec(#query)
SET #i = #i + 1
END;
If you're only expecting a single value, you could use a table variable. However, if multiple rows are created it effectively becomes a temporary table. If you think that's likely, declare as a temporary table.

How to select each row into a variable in SQL Server

We have a function that turns a delimited list into a table:
select * from dbo.fn_rpt_ParseValues('abc|123|test','|')
Results:
abc
123
test
How can I get each row into a SQL variable? For example:
#Name = 'abc'
#Phone = '123'
#Comment = 'test'
Thanks!
declare #S varchar(100) = 'abc|123|test'
declare #Name varchar(10)
declare #Phone varchar(10)
declare #Comment varchar(10)
select #Name = X.value('x[1]', 'varchar(10)'),
#Phone = X.value('x[2]', 'varchar(10)'),
#Comment = X.value('x[3]', 'varchar(10)')
from (select cast('<x>'+replace(#S, '|', '</x><x>')+'</x>' as xml)) as T(X)
select #Name, #Phone, #Comment
DECLARE #Split table(
RowIndex int IDENTITY(1,1)
,Item varchar(200));
INSERT INTO #Split
SELECT * from dbo.fn_rpt_ParseValues('abc|123|test','|');
DECLARE #Name varchar(50);
DECLARE #Phone varchar(50);
DECLARE #Comment varchar(100);
SET #Name = (SELECT Item FROM #Split WHERE RowIndex=1);
SET #Phone = (SELECT Item FROM #Split WHERE RowIndex=2);
SET #Comment = (SELECT Item FROM #Split WHERE RowIndex=3);
Assuming that the rows are ordered, you want to do a pivot to turn them into columns.
Another option is to have your parse function (or a modified version) return a single row result set (table-valued function) and use CROSS/OUTER APPLY to append them to a row:
http://msdn.microsoft.com/en-us/library/ms174853.aspx