Unable insert in dynamic query - sql

I have a Dynamic Query.
create procedure SP_InsertGroup
(
#GroupID nvarchar(50)
,#GroupName nvarchar(max)
,#ParentId int
,#Username nvarchar(50)
)
Declare #Insertstring nvarchar(max);
set #Insertstring='INSERT INTO GroupDetails
(GroupID
,GroupName
,CreatedBy
,CreatedOn
,ParentID
,IsActive
)
values('+#GroupID+',
'''+#GroupName+''',
'''+#Username+''' ,
getdate(),
'+#ParentID+',
1,
)'
execute sp_executesql #query=#Insertstring
GroupDetails table accept nulls for all columns...but wen i exec the stored procedure in this way..
exec Sp_insertGroup '1',null,'1',null
I am unable to insert.why does this doesnt work in Dyanmic query please help me...

You don't need dynamic SQL
create procedure SP_InsertGroup
#GroupID nvarchar(50)
,#GroupName nvarchar(max)
,#ParentId int
,#Username nvarchar(50)
AS
INSERT GroupDetails
(GroupID
,GroupName
,CreatedBy
,CreatedOn
,ParentID
,IsActive
)
values(#GroupID, #GroupName, #Username, getdate(), #ParentID, 1)
GO
I'd also have defaults for CreatedOn and IsActive on the table

The reason it isn't working is that when you are building your dynamic SQL string and some of the elements are null, it makes the whole string null.
To fix it, you need to wrap any nullable elements with ISNULL(#param, 'null').
But don't do this, do what #gbn says.

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

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 : 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.

SQL Server: Return uniqueidentifier from stored procedure

Can I return UNIQUEIDENTIFIER from a stored procedure using the RETURN statement or is it only by using the OUTPUT statement?
i.e to return the PersonID UNIQUEIDENTIFIER:
CREATE PROCEDURE CreatePerson
#Name NVARCHAR(255),
#Desc TEXT
AS
DECLARE #Count INT
DECLARE #JobFileGUID UNIQUEIDENTIFIER
-- Check if job exists?
SET #Count = (SELECT COUNT(Name) AS Name FROM Person WHERE Name=#Name)
IF #Count < 1
BEGIN
SET #PersonGUID = NEWID();
INSERT INTO Person
(PersonID, Name, [Desc])
VALUES (#PersonGUID, #Name, #Desc)
END
SELECT #PersonGUID = Person.PersonID
FROM Person
WHERE Name = #Name
RETURN #PersonGUID
GO
Thanks
In stored procedure - only using the OUTPUT statement. In function - return.
Use:
CREATE PROCEDURE CreatePerson
#Name NVARCHAR(255),
#Desc TEXT,
#PersonGUID UNIQUEIDENTIFIER OUTPUT
AS
BEGIN
SET #PersonGUID = ...
END
How to call:
DECLARE
#name NVARCHAR(255),
#desc TEXT,
#personGUID UNIQUEIDENTIFIER
SET #name = 'Bob'
SET #desc = 'One handsome man.'
EXEC [Database].[schema].CreatePerson #name, #desc, #personGUID OUTPUT
From the documentation you can actually see that a return in a stored procedure is actually used as a response code, hence you get the exception when trying to return a uniqueidentifier.
https://learn.microsoft.com/en-us/sql/relational-databases/stored-procedures/return-data-from-a-stored-procedure?view=sql-server-ver16#return-data-using-a-return-code
How I solved it, is by just performing a SELECT after the insert of the generated unique identifier.
DECLARE #ReportId UNIQUEIDENTIFIER;
SET #ReportId = NEWID();
INSERT INTO [dbo].[Report]
([ReportId]
,[ReportName])
VALUES
(#ReportId
,#ReportName)
SELECT #ReportId as ReportIdInternal
You'll have to see how to perform that with multiple selects though.
CREATE TABLE [dbo].[tbl_Clients]( [ClientID] [uniqueidentifier] NULL, [ClientName] varchar NULL, [ClientEnabled] [bit] NULL ) ON [PRIMARY]
GO
CREATE PROCEDURE [dbo].[sp_ClientCreate] #in_ClientName varchar(250) = "New Client 123", #in_ClientEnabled bit, #out_ClientId uniqueidentifier OUTPUT AS
SET #out_ClientId = NEWID();
INSERT INTO tbl_Clients(ClientId, ClientName, ClientEnabled) VALUES( #out_ClientId, #in_ClientName, #in_ClientEnabled)
DECLARE #return_value int, #out_ClientId uniqueidentifier
EXEC #return_value = [dbo].[sp_ClientCreate] #in_ClientName = N'111', #in_ClientEnabled = 1, #out_ClientId = #out_ClientId OUTPUT
SELECT #out_ClientId as N'#out_ClientId'
SELECT 'Return Value' = #return_value
GO
Result:-59A6D7FE-8C9A-4ED3-8FC6-31A989CCC8DB

T-SQL: How to use parameters in dynamic SQL?

I have the following dynamic query which is working fine without the WHERE clause, which is expecting UNIQUEIDENTIFIER.
When I pass it in, I don't get a result. I tried CAST and CONVERT, but no result. I might be doing it wrong, can anybody help?
CREATE PROCEDURE [dbo].[sp_Test1] /* 'b0da56dc-fc73-4c0e-85f7-541e3e8f249d' */
(
#p_CreatedBy UNIQUEIDENTIFIER
)
AS
DECLARE #sql NVARCHAR(4000)
SET #sql ='
DECLARE #p_CreatedBY UNIQUEIDENTIFIER
SELECT
DateTime,
Subject,
CreatedBy
FROM
(
SELECT
DateTime, Subject, CreatedBy,
ROW_NUMBER() OVER(ORDER BY DateTime ) AS Indexing
FROM
ComposeMail
WHERE
CreatedBy = #p_CreatedBy /* <--- the problem is in this condition */
) AS NewDataTable
'
EXEC sp_executesql #sql
You must pass in the parameters to sp_executesql. See MSDN for details.
...
WHERE
CreatedBy = #p
...
EXECUTE sp_executesql #sql, N'#p UNIQUEIDENTIFIER', #p = #p_CreatedBY
Multiple parameter syntax. Maybe this will save someone an extra Google Search:
exec sp_executesql
#qry,
N'#value1 int, #value2 int, #currentValue int',
#value1 = #value1, #value2 = #value2, #currentValue = #currentValue
DECLARE #ParmDefinition NVARCHAR(500)
SET #ParmDefinition = '#p_CreatedBy UNIQUEIDENTIFIER'
EXEC sp_executesql #sql, #ParmDefinition, #p_CreatedBy = #p_CreatedBy
I'm not sure if your variable is getting populated in string format or binary, but you may need to quote the uniqueidentifier in your where clause. If you just select the uniqueidentifier field, does it come back as string or binary?