I have tried to write the store procedure with some condition check inside the Where syntax.
But it only shows the status of the query instead of result.
Could any body help to resolve this issue.
Please find the query
declare #query varchar(200)
declare #option varchar(10) = 'A'
set #query ='select * from TableName'+
(case when #query = ''
then
'where ColumnName = 1 '
end)
execute sp_sqlexec #query
Your query should be
declare #query varchar(200)
declare #option varchar(10) ='A'
declare #search as int=1
select #query ='select * from TableName '+
case when #option ='A'
then
' where ColumnName = '+ cast(#search as varchar(200))
else ''
end
execute sp_sqlexec #query
see demo
What i can see for sure is lack of space before where condition.
declare #query varchar(200)
declare #option varchar(10) = 'A'
set #query ='select * from TableName'+
(case when #query = ''
then
' where ColumnName = 1 '
end)
You can try like this :
declare #query varchar(200)
declare #option varchar(10) = 'A'
set #query ='select * from TableName '
if #option ='A'
set #query = #query + ' where ColumnName = 1 '
--print #query
execute sp_sqlexec #query
declare #query nvarchar(max)
, #option varchar(10) = 'A';
set #query = N'select * from TableName '
+ CASE WHEN #option IS NOT NULL
THEN N' where ColumnName = 1 ' ELSE N'' END
execute sp_executesql #query;
Avoid using sp_sqlexec it is very old and not supported anymore, use sp_executesql instead.
Related
I was looking how I can parameterize table names and so I found dynamic sql queries. I finally got the proc saved, but when I execute it errors out with "Conversion failed when converting the varchar value ' AND ID =' to data type int." I have no idea what is going wrong when I try to execute this stored proc. I feel like it must be a typo but I cannot tell. The stored pro.
EDITED to incorporate the suggestion below. Still no luck unless I am doing this wrong.
-- =======================================================
-- Create Stored Procedure Template for Azure SQL Database
-- =======================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Author, , Name>
-- Create Date: <Create Date, , >
-- Description: <Description, , >
-- =============================================
ALTER PROCEDURE [dbo].[sp_GetFormFieldCDC]
(
#formfieldId INT,
#C___operation INT,
#C___start_lsn binary(10),
#tablename NVarchar(255)
)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON
DECLARE #ActualTableName AS NVarchar(255)
SELECT #ActualTableName = QUOTENAME( TABLE_NAME )
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = #tablename
DECLARE #sql AS NVARCHAR(MAX)
SELECT #sql = 'SELECT * FROM ' + #ActualTableName + ' WHERE __$start_lsn =' + CONVERT(NVARCHAR(255),#C___start_lsn) + ' AND __$operation =' + #C___operation + ' AND ID =' + #formfieldId + ';'
-- Insert statements for procedure here
EXEC sp_executesql #SQL, N' #formfieldId INT,
#C___operation INT,
#C___start_lsn binary(10),
#tablename NVarchar(255)', #formfieldId ,
#C___operation,
#C___start_lsn,
#tablename
END
GO
You should pass the parameters all the way through to sp_executesql. Do not inject them, unless they are object names, in which case you need QUOTENAME.
You can also use OBJECT_ID to check for table existence, and throw an exception if there is no such object.
CREATE OR ALTER PROCEDURE [dbo].[GetFormFieldCDC]
(
#formfieldId INT,
#C___operation INT,
#C___start_lsn binary(10),
#schemaname sysname,
#tablename sysname
)
AS
SET NOCOUNT ON;
IF (OBJECT_ID(QUOTENAME(#schemaname) + '.' + QUOTENAME(#tablename)) IS NULL)
THROW 50000, 'Table not found', 0;
DECLARE #sql AS NVARCHAR(MAX) = '
SELECT *
FROM ' + QUOTENAME(#schemaname) + '.' + QUOTENAME(#tablename) + '
WHERE __$start_lsn = #C___start_lsn
AND __$operation = #C___operation
AND ID = #formfieldId;
';
EXEC sp_executesql #SQL,
N' #formfieldId INT,
#C___operation INT,
#C___start_lsn binary(10)',
#formfieldId = #formfieldId,
#C___operation = #C___operation,
#C___start_lsn = #C___start_lsn;
GO
DECLARE #caseId UNIQUEIDENTIFIER,
#fieldId UNIQUEIDENTIFIER,
#columnName NVARCHAR(MAX),
#dateValue DATETIME,
#tableName nvarchar(MAX);
set #command = 'update ' + #tableName + ' set ' + #columnName + ' = ' + #dateValue + ' where Id = ''' + #caseId + '''';
exec sp_executesql #command;
Getting error while running the update command. - The data types datetime and uniqueidentifier are incompatible in the add operator.
Can someone help?
I think that you should use query parameters for the date and id values rather than mungling them in the query string.
That would look like:
declare
#pCaseId UNIQUEIDENTIFIER,
#pFieldId UNIQUEIDENTIFIER,
#pColumnName NVARCHAR(MAX),
#pDateValue DATETIME,
#pTableName nvarchar(MAX);
set #command = 'update ' + #pTableName + ' set ' + #pColumnName + ' = #dateValue where Id = #caseId';
exec sp_executesql
#command,
N'#dateValue DATETIME, #caseId UNIQUEIDENTIFIER',
#pDateValue,
#pCaseId
;
Try this:
DECLARE #caseId UNIQUEIDENTIFIER,
#fieldId UNIQUEIDENTIFIER,
#columnName NVARCHAR(MAX),
#dateValue DATETIME,
#tableName nvarchar(MAX);
set #command = 'update ' + #tableName + ' set ' + #columnName + ' = ' +convert(nvarchar(100),#dateValue,120) + ' where Id = ''' + #caseId + '''';
exec sp_executesql #command;
I have string variable in c#
String Condition = " And LoginName like ''%"+txtLoginName.text+"%''";
I pass this condition variable to a stored procedure like this:
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "GetAllUserMasterBySearch";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Condition ", Condition );
And my stored procedure is here:
create PROCEDURE [dbo].[GetAllUserMasterBySearch] (
#Condition nvarchar(max)
)
as
declare #Query nvarchar(max)
set #Query = 'SELECT
[UserMasterId], [LoginName], [UserName],
[UserType], [MobileNo], [Email],
[IsLogin], [IpAddress]
FROM
UserMaster
WHERE
IsActive = 1 ' + #Condition
print #query
EXEC sp_executesql #Query
How to pass "like" condition from C# ?
You can pass only variable and rewrite your SP as following
alter PROCEDURE [dbo].[GetAllUserMasterBySearch] (
#var nvarchar(max)
) as
declare #Query nvarchar(max)
set #Query = 'SELECT
[UserMasterId]
,[LoginName]
,[UserName]
,[UserType]
,[MobileNo]
,[Email]
,[IsLogin]
,[IpAddress]
FROM
UserMaster
WHERE
IsActive=1 AND LoginName LIKE %' + #var + '%';
print #query
EXEC sp_executesql #Query
Update: If you want to play with dynamic SQL then try ''' instead of ''. Honestly I haven't deal with dynamic SQL for a while since it it terrible and not secure approach (as it was already mentioned in comments)
My sql query returns the below output.
In C#.Net i have to convert it like below based on RowSequence and ColumnSequence column values.
How to do it.
you have to use dynamic pivot as your row value that needs to pivoted is not fixed:
DECLARE #columns AS NVARCHAR(MAX), #query AS NVARCHAR(MAX)
select #columns = STUFF((SELECT ', ' + QUOTENAME(ColumnName)
from YOURTABLE
group by ColumnName, ColumnSequesnce
order by ColumnSequesnce
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = N'SELECT ' + #columns + N' from
(
select RowSequence, ColumnValue, ColumnName
from YOURTABLE
) x
pivot
(
max(ColumnValue)
for ColumnName in (' + #columns + N')
) p '
exec sp_executesql #query;
You can go for Pivot in Sql
http://blog.sqlauthority.com/2008/06/07/sql-server-pivot-and-unpivot-table-examples/
Try it.
I want to PassColumn name as a paremeter in My SP
And if my tat column exists in first table (Batch_Master), want to fatch value from that column,
And if that column exists in my second table (GTIN_Master), want to fetch value from tat table column,
Each table have columns like..
Batch_Master (Batch_M_id, GTIN(primary key),....etc
GTIN_Master (GTIN (foreign key),..etc)
I have Batch_M_id, and column name as a parameter..
Note: column Name having random datatype, some time int or some time datetime etc
I Try followin SP
CREATE PROCEDURE dbo.StoredProcedure2
#columnName varchar(50),
#batchmId int
AS
if exists(select * from sys.columns
where Name = N'columnName' and Object_ID = Object_ID(NBatch_Master'))
begin
select #columnName from Batch_Master
end
else
begin
select #columnName
from GTIN_Master inner join Batch_Master
on GTIN_Master.GTIN = Batch_Master.GTIN
where Batch_M_id =#batchmId
end
RETURN
What you need when you do not know exactly the query structure you are going to execute, then you have to create a dynamic query, which is actually a form of templating queries.
CREATE PROCEDURE dbo.StoredProcedure2
#columnName varchar(50),
#batchmId int
AS
DECLARE #SQL1 AS VARCHAR(MAX)
DECLARE #SQL2 AS VARCHAR(MAX)
SET #SQL1 = 'select ' + #columnName + ' from Batch_Master'
SET #SQL1 = 'select ' + #columnName + '
from GTIN_Master inner join Batch_Master
on GTIN_Master.GTIN = Batch_Master.GTIN
where Batch_M_id =' + CONVERT(VARCHAR,#batchmId)
IF EXISTS(SELECT * FROM sys.columns WHERE Name = #columnName and Object_ID = Object_ID(N'Batch_Master'))
BEGIN
EXEC (#SQL1)
END
ELSE
BEGIN
EXEC (#SQL2)
END
The above will do what you want but is prone to errors. For instance what if the column passed in the parameter does not exist in the tables used in the second query? You should probably need to check for existence in the second case too.
DECLARE #SQL VARCHAR(MAX)
SET #SQL = 'select ' + #columnName + ' from Batch_Master'
EXECUTE(#SQL)
This SQL:
set nocount on
go
create table One (id int, name varchar(25))
go
create table Two (id int, value varchar(25))
go
insert into One values (1, 'Table One')
insert into Two values (1, 'Table Two')
go
create procedure sp_test_colname
#colname sysname
as
declare #sql nvarchar(2048)
if exists (select 1 from sys.columns where name = #colname and object_id = object_id(N'One'))
set #sql = 'select [' + #colname + '] from [One]'
else
if exists (select 1 from sys.columns where name = #colname and object_id = object_id(N'Two'))
set #sql = 'select [' + #colname + '] from [Two]'
if #sql <> ''
exec sp_executesql #sql
go
exec sp_test_colname 'name'
exec sp_test_colname 'value'
exec sp_test_colname 'somethingelse'
go
drop procedure sp_test_colname
drop table One, Two
Returns the following:
name
-------------------------
Table One
value
-------------------------
Table Two