How to set mutliple variables using SELECT and CASE - sql

I am trying to set variables in my stored procedure when the passed parameter is a certain value like this:
ALTER PROCEDURE [dbo].[Procedure1]
(
#ID int,
#WatchType varchar(100)
)
AS
SET NOCOUNT ON
DECLARE #stock int
DECLARE #price float
DECLARE #details varchar(max)
CASE #WatchType
WHEN 'TIMEX' THEN
(SELECT #stock= Stock,
#price= Price,
#details= Details,
FROM tblWatches WHERE Uid= #ID)
ELSE
END
I keep getting an error when I try to parse it. Does anyone know why?

ALTER PROCEDURE [dbo].[Procedure1]
(
#ID int,
#WatchType varchar(100)
)
AS
SET NOCOUNT ON
DECLARE #stock int
DECLARE #price float
DECLARE #details varchar(max)
IF #WatchType = 'TIMEX'
BEGIN
(SELECT #stock= Stock,
#price= Price,
#details= Details,
FROM tblWatches WHERE Uid = #ID)
END

Related

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

SQL Server : Dynamic Query in Stored Procedure in

I tried to write dynamic query in SQL Server. However I get warning like below,
The Selected stored procedure or function returns no columns
I have been trying to achieve this however it still does not run.
Where did I miss ?
ALTER PROCEDURE [dbo].[S_ProjeGetir1]
#ID int=0,
#AktifMi int,
#ProjeFirma int,
#Icinde int,
#AramaText Varchar(500),
#Arasinda1 Varchar(50),
#Arasinda2 Varchar(50)
AS
BEGIN
Create Table #TempTable
(Sonuc int
,ID int
,FirmaID int
,PrismProjeID int
,ProjeAdi nvarchar(150)
,RgID uniqueidentifier
,HaritaEnlem nvarchar(25)
,HaritaBoylam nvarchar(25)
,ProjeTeslimTarihi datetime
,HemenTeslimMi bit
,Adres nvarchar(250)
,AdresUlkeID int
,AdresILID int
,AdresILceID int
,AdresSemtID int
,KonutSayisi int
,LansmanTarihi datetime
,OfisSayisi int
,MagazaSayisi int
,BlokSayisi int
,YesilAlan int
,KrediyeUygunMu bit
,AktifMi bit
,UcBoyutVarMi bit
,UlkeAdi nvarchar(150)
,Sehir nvarchar(50)
,Ilce nvarchar(50)
,Semt nvarchar(50)
,FirmaAdi nvarchar(100)
,StokSonGuncellemeTarihi datetime)
Declare #SqlText varchar(8000),
#AktifPasif bit
Set #AktifPasif=Case When #AktifMi=0 Then 1 When #AktifMi=1 Then 0 End
SET NOCOUNT ON
BEGIN TRY
Set #SqlText=' SELECT 1 Sonuc ,[ID],[FirmaID] ,[PrismProjeID],[ProjeAdi] ,[RgID] ,[HaritaEnlem] ,[HaritaBoylam] ,[ProjeTeslimTarihi]
,[HemenTeslimMi],[Adres] ,[AdresUlkeID] ,[AdresILID] ,[AdresILceID] ,[AdresSemtID] ,[KonutSayisi]
,[LansmanTarihi],[OfisSayisi] ,[MagazaSayisi],[BlokSayisi],[YesilAlan] ,[KrediyeUygunMu],[AktifMi]
,[UcBoyutVarMi] ,[UlkeAdi] ,[Sehir] ,[Ilce] ,[Semt]
,[FirmaAdi] ,[StokSonGuncellemeTarihi]
FROM [dbo].[V_Proje] AS P WITH (NOLOCK)
WHERE 1=1 '
If #ID>0 Set --ID ye Göre İlgili Kayıdı almak için
#SqlText=#SqlText +' and ID=' +cast(#ID as Varchar(50))
Else
Begin
--Aktif ise veya Pasif ise
if #AktifMi=0 or #AktifMi=1
Begin
Set #SqlText=#SqlText +' and AktifMi='+cast(#AktifPasif as varchar(50))
End
--Bütün Alanları sorgulamak için
Set #SqlText=#SqlText +' and CASE WHEN '+cast(#ProjeFirma as varchar(50))+'=1 THEN Upper(ProjeAdi)
WHEN '+cast(#ProjeFirma as varchar(50))+'=0 THEN Upper(FirmaAdi)
WHEN '+cast(#ProjeFirma as varchar(50))+'=2 THEN Upper(HaritaEnlem)
WHEN '+cast(#ProjeFirma as varchar(50))+'=3 THEN Upper(HaritaBoylam)
WHEN '+cast(#ProjeFirma as varchar(50))+'=4 THEN Upper(Adres)'
If #Icinde=0--İçinde
Set #SqlText=#SqlText +' END Like ''%'+#AramaText+'%'' '
If #Icinde=1--İle Başlayan
Set #SqlText=#SqlText +' END Like '''+#AramaText+'%'' '
If #Icinde=2--Arasında
Set #SqlText=#SqlText +' END between '''+ #Arasinda1+''' and '''+#Arasinda2+''''
--select #SQLTEXT
End
exec('insert into #TempTable ' + #SqlText)
Select Sonuc, [ID],[FirmaID],[PrismProjeID],[ProjeAdi] ,[RgID] ,[HaritaEnlem],[HaritaBoylam],[ProjeTeslimTarihi],[HemenTeslimMi]
,[Adres] ,[AdresUlkeID] ,[AdresILID],[AdresILceID] ,[AdresSemtID],[KonutSayisi] ,[LansmanTarihi] ,[OfisSayisi]
,[MagazaSayisi],[BlokSayisi] ,[YesilAlan],[KrediyeUygunMu],[AktifMi] ,[UcBoyutVarMi],[UlkeAdi],[Sehir] ,[Ilce],[Semt]
,[FirmaAdi] ,[StokSonGuncellemeTarihi]
From #TempTable AS T WITH (NOLOCK)
END TRY
BEGIN CATCH
SELECT -1 AS Sonuc -- EXCEPTION
END CATCH
SET NOCOUNT OFF
END
Any help will be appreciated.
Thanks
I am not sure if what i am going to tell is going to work for EF, but i had a similar case in LINQ to SQL classes.
Backup the code of your Stored Procedure
Create a single SELECT statement with appropriate values, in your Stored Procedure like the following:
ALTER PROCEDURE [dbo].[S_ProjeGetir1]
#ID int=0,
#AktifMi int,
#ProjeFirma int,
#Icinde int,
#AramaText Varchar(500),
#Arasinda1 Varchar(50),
#Arasinda2 Varchar(50)
AS
BEGIN
Select CONVERT(VARCHAR(30),'') AS Sonuc, -- Make sure to convert to what your
0 AS [ID],
0 AS [FirmaID],
0 AS [PrismProjeID],
...
END
Import this Stored Procedure in EF
If all goes well, restore the backed up code in the Stored Procedure.

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.

Update a Table by Passing Table Name, ColumnName as a Variable Using Cursor

I want to Update a Table. I am getting Table Name and Column Name as a XML DataSet from the Front End. I have written One Cursor for that. But it throws error. Below is my Cursor
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[PMT_Formstatus_Update_Test]
(
#XMLTableNames VARCHAR(MAX)
)
AS
BEGIN
DECLARE #docHandle INT, #ErrorMessage VARCHAR(200), #doc VARCHAR(200)
SET #doc = '<?xml version="1.0" encoding="iso-8859-1" ?>'
DECLARE #Names TABLE
(
TName VARCHAR(50),
CName VARCHAR(50),
IDField VARCHAR(50),
FunctionID INT,
ID INT,
StatusID INT
)
SET #XMLTableNames = #doc + #XMLTableNames
EXEC sp_xml_preparedocument #docHandle OUTPUT, #XMLTableNames
INSERT INTO #Names
SELECT * FROM
OPENXML(#docHandle,'NewDataSet/NameDetails',2)
WITH
(
TName VARCHAR(50),
CName VARCHAR(50),
IDField VARCHAR(50),
FunctionID INT,
ID INT,
StatusID INT
)
DECLARE #FunctionID INT
DECLARE #StatusID INT
DECLARE #ID INT
DECLARE #TableName VARCHAR(50)
DECLARE #ColumnName VARCHAR(50)
DECLARE #IDField VARCHAR(50)
DECLARE #getTables CURSOR
SET #getTables = CURSOR FOR
SELECT FunctionID, TName, CName, StatusID, IDField, ID FROM #Names
OPEN #getTables
FETCH NEXT
FROM #getTables INTO #FunctionID, #TableName, #ColumnName, #StatusID, #IDField, #ID
WHILE ##FETCH_STATUS = 0
BEGIN
UPDATE #TableName SET #ColumnName = 3 WHERE #IDField = #ID
FETCH NEXT
FROM #getTables INTO #FunctionID, #TableName, #ColumnName, #StatusID, #IDField, #ID
END
CLOSE #getTables
DEALLOCATE #getTables
END
How to write Update Query in this case? Please I need all your suggestions...
You need to concatenate them as string then call EXEC('')
EXEC ('UPDATE TableName SET ColumnName1 = 3 WHERE ColumnName2= Value')
Simple Dynamic SQL Example:
DECLARE #SQL NVARCHAR(max),#TableName VARCHAR(128),#ColumnName1 VARCHAR(128),#ColumnName2 VARCHAR(128),#Value NVARCHAR(MAX),#NewValue NVARCHAR(MAX)
SET #TableName='User'
SET #ColumnName1='Session_Id'
SET #ColumnName2='Session_Id_Old'
SET #Value=''''+CAST(NEWID() as NVARCHAR(50))+''''
SET #NewValue=''''+CAST(NEWID() as NVARCHAR(50))+''''
SET #SQL=
REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
'UPDATE [#TableName] SET [#ColumnName1] = #NewValue WHERE [#ColumnName2]= #Value','#TableName',#TableName),
'#ColumnName1',#ColumnName1),'#Value',#Value),'#NewValue',#NewValue),'#ColumnName2',#ColumnName2)
EXECUTE(#SQL)
You should add apostrophes to both sides of old/new values if data types are strings
You can hopefully see why what you've written doesn't work, since it's an update statement to execute against a table variable, which affects no actual columns in that table:
declare #TableName table (ID int not null)
declare #ColumnName1 int
declare #ColumnName2 int
declare #Value int
UPDATE #TableName SET #ColumnName1 = 3 WHERE #ColumnName2= #Value
One means to try and achieve what you're doing are dynamic SQL. It's ugly (and will be more so if the data types in the columns vary). There's no real "meta-programming" system built into T-SQL.

Create function dynamically in a database

HI i need to create a function dynamically in a database..My procedure accepts Database name as a parameter, then i need to create this function dynamically in that DATABASE.
But i am unable to execute this..please help me.Regards in advance
Create procedure [dbo].[Sp_Insertfun]
(
#OrgName nvarchar(100)
)
AS BEGIN
Declare #orgdataInsertString nvarchar(max);
set #orgdataInsertString='Use '+#OrgName+'' ;
set #orgdataInsertString=#orgdataInsertString+char(13)+char(10)+'GO'+'
Create function dbo.[fn_GroupDisplay](#GroupID int)
RETURNS #Group TABLE
(
GrpPath nvarchar(max)
)
as
begin
declare #ParentId1 int
declare #ParentId2 varchar(50)
declare #ParentId3 varchar(50)
declare #parentId4 varchar(50)
declare #Text nvarchar(max)
set #ParentId3=''''
begin
set #ParentId1=(select ParentID from GroupDetails where GroupID=#GroupID)
set #ParentId4=(select GroupName from GroupDetails where GroupID=#GroupID)
while(#ParentId1>0)
begin
set #parentId2=(select GroupName from GroupDetails where GroupID=#ParentId1 )
set #ParentId3 = #ParentId2+ ''\'' + coalesce(#ParentId3,''')
set #ParentId1=(select ParentID from GroupDetails where GroupID=#ParentId1 )
end
set #Text=#ParentId3+#ParentId4
INSERT INTO #Group VALUES (#Text)
end
RETURN
end'
execute sp_executesql #query=#orgdataInsertString
print #orgdataInsertString
end