SQL Server : Dynamic Query in Stored Procedure in - sql

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.

Related

Dynamic Name for Database Table - Stored Procedure

I want to create dynamic name for my database tables. I declare variable and use it as my table name.
ERROR: Incorrect syntax near '#sample'. Expecting '.',ID or QUOTED_ID
CREATE PROCEDURE [dbo].[sp_SAMPLE]
#name nvarchar(50)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #sample nvarchar(50);
SET #sample = 'tbl_function_' + #name;
Create Table #sample
(
id int not null,
UserType nvarchar(50) null,
paramater2 nvarchar(50) null
)
END
Is there any way to make my table name dynamic? Thank you.
I'm not sure why you would want to do this. But, you can do it using dynamic SQL:
CREATE PROCEDURE [dbo].[sp_SAMPLE]
#name nvarchar(50)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #sql nvarchar(max);
SET #sql = '
Create Table tbl_function_#name
(
id int not null,
UserType nvarchar(50) null,
paramater2 nvarchar(50) null
)';
SET #sql = REPLACE(#sql, '#name', #name);
EXEC sp_executesql #sql;
END;
Why would you want to create a separate table for each #name, instead of just inserting rows with #name in a column?
CREATE PROCEDURE [dbo].[sp_SAMPLE]
#name nvarchar(50)
AS
BEGIN
SET NOCOUNT ON
DECLARE #sql varchar(4000);
SET #sql = '
Create Table tbl_function_'+#name+'
(
id int not null,
UserType nvarchar(50) null,
paramater2 nvarchar(50) null
)'
EXEC (#sql)
END

SQL Server stored procedure: verify CRUD operation success/failure using output variable

I am trying to create a SQL Server stored procedure to handle updates to a table using some dynamic SQL. The table name required for the update is stored in a table that correlates a table id to a category id. Once the table name is retrieved and the table id is not null, I update the table using a dynamic SQL query as shown below:
CREATE PROCEDURE [dbo].[SP_EBS_CustomForms_SetCategoryData]
(#flag int output,
#cat_id int,
#sort int,
#value varchar(50),
#active int,
#enum int)
AS
BEGIN
DECLARE #tbl as varchar(50)
DECLARE #tbl_id as int
DECLARE #sql nvarchar(max)
BEGIN TRY
SET #tbl_id = (SELECT [tbl_id]
FROM [demodata].[dbo].[ebscustomforms_cattable]
WHERE cat_id = #cat_id)
IF #tbl_id IS NOT NULL
BEGIN
SET #tbl = (SELECT table_name
FROM ebscustomforms_enumtable
WHERE tbl_id = #tbl_id)
SET #sql = 'UPDATE ' + #tbl + ' SET [sort_order] = #sort, [value] = #value, [active] = #active WHERE [enum_id] = #enum'
EXECUTE sp_executesql #sql, N'#sort int, #value varchar(50), #active int, #enum int', #sort, #value, #active, #enum
SET #flag = 0
RETURN #flag
END
END TRY
BEGIN CATCH
IF ##ERROR <> 0
BEGIN
SET #flag = 1;
RETURN #flag
END
END CATCH
END
I want this stored procedure to return an int value indicating whether the stored procedure was successful (0) or failed (1) updating the table.
Points of error are as follows:
#tbl_id variable is null
#tbl is either null or an empty varchar
The table to be updated does not have a record where [enum_id] = #enum
I have noticed that when I try to update a record that does not exist, the procedure seems to return as successful i.e. #flag = 0. However, I would imagine that an error should be thrown because the record does not exist.

SQL call a SP from another SP

Can I please have some help with the syntax of a SP in SQL.
Here is my code:
CREATE PROCEDURE usp_GetValue
(
#ID VARCHAR(10),
#Description VARCHAR(10)
)
AS
BEGIN
return #ID + #Description
END
CREATE PROCEDURE usp_InsertValue
(
#ID VARCHAR(10),
#FirstName VARCHAR(50),
#LastName VARCHAR(50),
#Description VARCHAR(10),
#Comment VARCHAR(max)
)
AS
BEGIN
Declare #v_Value VARCHAR(15)
Set #v_Value = usp_GetValue(#ID, #Description)
END
In the usp_InsertValue SP, I am wanting to declare and set a variable. Once the variable has been declared, I then wish to call another SP with parameters to set the value of the declared variable.
I am not sure of the syntax. May I please have some help?
UPDATE
I have updated my above code using your function. How do I Set the #v_Value from the usp_GetValue function.
I am getting this error:
'usp_GetValue' is not a recognized built-in function name.
UPDATE2
Here is my full code:
CREATE PROCEDURE usp_PersonCategoryLookupTesting
(
#ID VARCHAR(10),
#Description VARCHAR(10),
#res VARCHAR(10) OUTPUT
)
AS
BEGIN
return #ID + #Description
END
CREATE PROCEDURE usp_InsertPersonTesting
(
#IDTest VARCHAR(10),
#FirstName VARCHAR(50),
#LastName VARCHAR(50),
#AddressLine1 VARCHAR(50),
#AddressLine2 VARCHAR(50),
#AddressLine3 VARCHAR(50),
#MobilePhone VARCHAR(20),
#HomePhone VARCHAR(20),
#Description VARCHAR(10),
#Comment VARCHAR(max)
)
AS
BEGIN
Declare #PersonCategory VARCHAR(15)
EXEC usp_PersonCategoryLookupTest #ID, #Description, #PersonCategory
INSERT INTO Person(FirstName, LastName, AddressLine1, AddressLine2, AddressLine3, MobilePhone, HomePhone, DateModified, PersonCategory, Comment)
VALUES (#FirstName, #LastName, #AddressLine1, #AddressLine2, #AddressLine3, #MobilePhone, #HomePhone, GETDATE (), #PersonCategory, #Comment)
END
I am getting this error in my application that is calling the SQL code:
Conversion failed when converting the varchar value '123Client' to data type int.
I am using the values "123" and "Client" for #IDTest and #Description.
I think output parameters should be the proper way:
See this post:
stored procedure returns varchar
CREATE PROCEDURE usp_GetValue
(
#ID VARCHAR(10),
#Description VARCHAR(10),
#res VARCHAR(10) OUTPUT
)
AS
BEGIN
return #ID + #Description
END
CREATE PROCEDURE usp_InsertValue
(
#ID VARCHAR(10),
#FirstName VARCHAR(50),
#LastName VARCHAR(50),
#Description VARCHAR(10),
#Comment VARCHAR(max)
)
AS
BEGIN
Declare #v_Value VARCHAR(15)
EXEC usp_GetValue #ID, #Description, #v_Value
-- use #v_Value here...
END
You can only use a function like that, not stored procedure. Stored Procedures only return integer values.
For SP, you need to create out parameters to retrieve the values. For this scenario, it is better to create a function
CREATE FUNCTION usp_GetValue
(
#ID VARCHAR(10),
#Description VARCHAR(10),
)
RETURNS VARCHAR(50)
AS
BEGIN
return #ID + #Description
END
Then call it:
SET #v_value = dbo.usp_GetValue('John','Doe') --output: John Doe
If you insist you want a SP, which is not proper for this, there are 2 ways
1) An out parameter
CREATE PROCEDURE usp_GetValue
(
#ID VARCHAR(10),
#Description VARCHAR(10),
#Result varchar(20) OUTPUT
)
AS
BEGIN
SET #Result = #ID + #Description
END
Then call it:
Declare #v_Value VARCHAR(15)
Set #v_Value = EXEC usp_GetValue #ID, #Description, #v_Value OUTPUT
2) Select from it
CREATE PROCEDURE usp_GetValue
(
#ID VARCHAR(10),
#Description VARCHAR(10)
)
AS
BEGIN
SELECT #ID + #Description
END
Use it like this:
declare #tempresult as table(v_value as varchar(15))
INSERT INTO #tempresult
EXEC usp_GetValue #ID, #Description
Select Top 1 #v_value = v_value From #tempresult
My advise is use the function approach.

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