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
Related
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
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.
This question already has an answer here:
Get value output from SQL Server stored procedure into variable
(1 answer)
Closed 9 years ago.
i have a Hierarchy of stored procedures calling one in another as below:
1
2
3
Now what i am doing is:
first of all i am showing the 1st level sp .
Create proc proc_test3
(
#Id uniqueidentifier,
#value varchar(100)
)
as
declare #Outputvalue varchar(100)
if #Id='2'
begin
exec #Outputvalue= proc_test2 #Id #value
select #Outputvalue
end
Here is the second level :
Create proc proc_test2
(
#Id uniqueidentifier,
#value varchar(100)
)
as
declare #Outputvalue varchar(100)
if #Id='2'
begin
exec #Outputvalue= proc_test1 #Id #value
select #Outputvalue
end
and here is last 3rd level :
Create proc proc_test1
(
#Id uniqueidentifier,
#value varchar(100)
)
as
update tblsample set value=#value where id=#Id
select 1
I have paste just an example but in-actual my code is much complex to read, so i have implemented it in some simpler way so that every can understand it easily,
Now what is my problem:
every time i got #Outputvalue=0 when i execute the "proc_test3", please help me so that i can come out from this prob, if i am doing the things in some wrong way please let me know the right way, please help me resolve the issue.
Try to use RETURN construction -
CREATE PROC proc_test3
(
#Id UNIQUEIDENTIFIER,
#value VARCHAR(100)
)
AS BEGIN
IF #Id = '2' BEGIN
DECLARE #Outputvalue VARCHAR(100)
EXEC #Outputvalue = dbo.proc_test2 #Id, #value
RETURN #Outputvalue
END
END
CREATE PROC proc_test2
(
#Id UNIQUEIDENTIFIER,
#value VARCHAR(100)
)
AS BEGIN
IF #Id='2' BEGIN
DECLARE #Outputvalue VARCHAR(100)
EXEC #Outputvalue= proc_test1 #Id, #value
RETURN #Outputvalue
END
END
CREATE PROC proc_test1
(
#Id UNIQUEIDENTIFIER,
#value VARCHAR(100)
)
AS BEGIN
UPDATE tblsample
SET value=#value
WHERE id=#Id
RETURN 1
END
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.
i have a following sql function which takes a string word as input it then checks whether the word is equal to a categoryName or not i want it to behave like when the if statement is true it breaks from the loop and return #temp_catid else it returns 0 or 1 how can i do that im new to sql scripting plz help... below is my function
USE [myDB]
GO
/****** Object: UserDefinedFunction [dbo].[udfisEqualToCategory] Script Date: 01/31/2011 10:57:56 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create FUNCTION [dbo].[udfisEqualToCategory](#word nvarchar(max))
RETURNS INT
AS
BEGIN
--declare a temp category table for data processing
declare #temptbl_category Table
(
indexx int identity(1,1),
categoryid int,
categoryname nvarchar(max)
)
--insert data from feedcrawler.category into temp category table
insert into #temptbl_category
select CategoryId,Name
from Category
--declare some variables to hold the data of current row of temp category table being processed while looping
declare #temp_catid int
declare #temp_catname nvarchar(max)
declare #rowcount int
set #rowcount=(select count(indexx)from #temptbl_category)
declare #I int
set #I=1
--print'given string-> '+ #FullName
--print'string length-> '+convert(nvarchar(max),#strlen)
while(#I <= #rowcount)
begin
select #temp_catname=categoryname,#temp_catid=categoryid from #temptbl_category where indexx=#I
set #temp_catname=lower(#temp_catname)
if(#word=#temp_catname)
begin
return #temp_catid
break
end--end if
set #I=#I+1
END--while loop ends
return 0
end-- function ends
GO
No need to loop, just search the table with WHERE
Create FUNCTION [dbo].[udfisEqualToCategory](#word nvarchar(max))
RETURNS INT
AS
BEGIN
declare #temp_catid int
select
#temp_catid = categoryid
from
Category
WHERE
LOWER(#word) = LOWER(categoryname);
--no match = #temp_catid IS NULL. So change to zero
RETURN ISNULL(#temp_catid, 0);
END
GO