sql stored procedure single quotes - sql

I have a stored procedure as below
create procedure TestTry
BEGIN
declare #query varchar(max)
SET NOCOUNT ON;
set #query = 'select * from table1 when RECORD_FLAG <> 't'
then Convert(Decimal(10,4),ISNULL(T.HISTORY_PCR ,0)) else '0'';
exec (#query)
end
Here after RECORD_FLAG <> I want to give it in single quotes and also give 0 in single quotes how to give that
The above shown is a sample in real time my query is big I have to give the query in #query only

Use '' (double) for ' (single)
set #query = 'select * from table1 when RECORD_FLAG <> ''t''
then Convert(Decimal(10,4),ISNULL(T.HISTORY_PCR ,0)) else ''0''';

create procedure TestTry
AS --<-- you'er also missing AS key word here
BEGIN
SET NOCOUNT ON;
declare #query varchar(max)
set #query = 'select * from table1 when RECORD_FLAG <> ''t''
then Convert(Decimal(10,4),ISNULL(T.HISTORY_PCR ,0)) else ''0''';
EXECUTE sp_executesql #query --<-- use this syntax to execute dynamic sql
end
Also you do not need to use dynamic sql for such a simple query,
dynamic sql is the devil of sql and you want to avoid using it
whenever possible.
Your Query
Also your query syntax isnt right you are trying to execute a query as follows
select *
from table1
when RECORD_FLAG <> 't' --<-- cant use WHEN without the CASE statement also you
--cannot use a Case statement here right after your table name

Related

SQL "if exists..." dynamic query

Suppose I have a query stored in a variable like this (it's actually dynamically populated and more complex, but this is for demonstration purposes):
DECLARE #Query VARCHAR(1000) = 'SELECT * FROM dbo.MyTable'
Is there a way to check if the query would return any results? Something like this, but this doesn't work:
IF EXISTS (#Query)
BEGIN
-- do something
END
The only way that I can think of to do this is to put the results in a temp table and then query from that, but that is not ideal because the columns in the dynamic query can vary and I really don't need the temp table at all for any reason other than checking whether some rows would be returned. Is there a better way?
Try Executing the Dynamic query and use ##RowCount to find the existence of rows.
DECLARE #Query NVARCHAR(1000) = 'SELECT * FROM [dbo].[Mytable]',
#rowcnt INT
EXEC Sp_executesql #query
SELECT #rowcnt = ##ROWCOUNT
IF #rowcnt > 0
BEGIN
PRINT 'row present'
END
Try this:
DECLARE #Query NVARCHAR(1000) = 'SELECT #C = COUNT(*) FROM dbo.MyTable'
DECLARE #Count AS INT
EXEC sp_executesql #Query, N'#C INT OUTPUT', #C=#Count OUTPUT
IF (#Count > 0)
BEGIN
END
I know this answer is too late. but, I'm leaving this here to help someone else to use IF EXISTS with a dynamic query.
This is how you should do it with dynamic queries.
DECLARE #Query VARCHAR(MAX)
SET #Query = 'SELECT * FROM [dbo].[MyTable]'
SET #Query = 'IF EXISTS (' + #Query + ')
BEGIN
-- do something
print ''1''
END
ELSE
BEGIN
-- do something else
print ''0''
END
'
exec (#Query)
Hope this helped someone. Vote if it did :)
You can use EXEC to execute sql statement, then call ##ROWCOUNT which Returns the number of rows affected by the last statement, to check row exists in sql select stetement.
DECLARE #Query VARCHAR(1000) = 'SELECT * FROM dbo.MyTable',#hasRow int
EXEC (#Query)
SELECT #hasRow =##ROWCOUNT // Returns the number of rows affected by the last statement
PRINT #hasRow
IF #hasRow > 0
BEGIN
Print 1
END
BEGIN
Print 2
END
Hi I think that only way is to put IF EXISTS part into code of execution. My case is to stop execution in point when select affects at least one row, that is goal of IF EXISTS.
Little example that saves reading all records covering by condition to first occurence:
set nocount off;
drop table if exists #temp
go
create table #temp (idCol int identity(1,1),someText nvarchar(1))
go
insert into #temp values ('a')
go 25000
declare #query nvarchar(max)
,#resultFork bit
set #query = 'if exists (select * from #temp where idCol % 3 = 0)
set #resultFork=1
else
set #resultFork=0'
print #query
exec sp_executeSQL #query, N'#resultFork int output', #resultFork=#resultFork output
print #resultFork
/*Now U can use #resultFork in simple if condition...
if #resultFork = 1
begin
--
end
else
begin
--
end
*/

Stored procedure to find number of rows in a table

In a stored procedure I pass a table name as the input variable.
I want to return the number of rows of this table with that stored procedure.
I tried something like this but it did not work:
declare #maxRowCount bigint
exec('set '+ #maxRowCount + ' =(select COUNT(1) from ' + #tableName + ')')
This is SQL Server 2008.
You can try this
CREATE PROCEDURE dbo.sp_selectcount
#tablename NVARCHAR(200)
AS
DECLARE #cmd NVARCHAR (255)
SET #cmd = 'SELECT count(*) from ' + #tablename
EXEC sp_executesql #cmd
The following example should give you something to work with.
-- fully qualify your table name (this is probably an input value in your sproc?)
-- please note that I use system view master.sys.tables as an example table here
DECLARE #tablename NVARCHAR(MAX) = N'[master].[sys].[tables]';
-- build the sql statement that you will execute
DECLARE #sql NVARCHAR(MAX) = N'SELECT COUNT(*) FROM ' + #tablename;
-- create a variable to hold the number of rows later on
DECLARE #nrofrows BIGINT;
-- create a temp table to store the result of executing the sql statement
CREATE TABLE #temp (NrOfRows BIGINT);
-- insert the result of the execution of the sql statement into the temp table
INSERT INTO #temp
EXECUTE(#sql);
-- extract the number of rows from the temp table
SET #nrofrows = (SELECT NrOfRows FROM #temp);
-- check the result so you can test!
PRINT #nrofrows;
If you want good background information on dynamic SQL, check out Erland Sommarskogs article The Curse and Blessings of Dynamic SQL.
You should remove the quotes around #maxRowCount.
Try this:
declare #maxRowCount bigint
exec('set #maxRowCount =(select COUNT(*) from ' + #tableName + ')')
OR
exec('SELECT #maxRowCount = COUNT(*) from ' + #tableName)
Analysis:
With the query you tried, it will execute:
set blablabla = (select count(1) from MyTable)
By removing the quotes:
set #maxRowCount = (select count(*) from MyTable)
You can try this instead.
declare #maxRowCount bigint(5)
exec('SELECT COUNT(*) INTO #maxRowCount FROM ' + #tableName)

Using sp_executesql without returning row sets

In a store procedure I am building dynamic SQL statement which is executed using sp_executesql procedure.
The dynamic SQL statement can be a store procedure, that:
do not return row set
do return one row set
do return multiple row sets
The initial store procedure itself returns other row sets. I want to return only them, and to not return the row sets from the internal procedure.
Generally, I want to force the following statement to do not return anything:
DECLARE #DynamicSQLStatement NVARCHAR(MAX)
SET #DynamicSQLStatement = N'SELECT 1 SELECT 2 SELECT 3 SELECT 4 SELECT 5'
EXEC sp_executesql #DynamicSQLStatement
Is there a way to do this?
I guess you can tweak your Store Procedures by doing something like this .
CREATE PROCEDURE usp_StopMessageProc
#StopMsg bit = 0
AS
BEGIN
SET NOCOUNT ON;
DECLARE #Sql VARCHAR(MAX);
SET #Sql = '';
SET #Sql = 'SELECT Column1, Column2, Column3.... ';
IF #StopMsg = 1
SET #Sql = #Sql + 'INTO #TempDeleteMe';
SET #Sql = #Sql +
'FROM dbo.SomeTable ';
EXEC(#Sql);
END
GO
By defualt your proc will do whatever it does best but when #StopMsg is set to 1 it suppress the return messages/Result sets.

Run SQL pre-defined function stored in table

I have a table which stores a SQL predefined function, like CONVERT(VARCHAR(10), '2012-08-21 00:16:41.993', 101) in a row/column. While retrieving the result from table, it should run the function and give the final outcome as "2012-08-21", instead right now it returns the same function statement. I am running select (select RunDate from RunDate) and using SQL server database.
Kindly help!!
You need to use dynamic SQL for this. You can't just nest expressions and have SQL evaluate the output...
DECLARE #x TABLE(sql NVARCHAR(255));
INSERT #x(sql) SELECT N'CONVERT(VARCHAR(10), ''2012-08-21 00:16:41.993'', 101)';
DECLARE #sql NVARCHAR(MAX);
SELECT #sql = N'SELECT ' + sql FROM #x;
EXEC sp_executesql #sql;
It would look like this (adjust accordingly):
DECLARE #predef VARCHAR(1000);
DECLARE #sqlquery VARCHAR(1000);
SELECT #predef = (SELECT top 1 Value FROM Parameters Where Name = 'MYFUNC');
SET #sqlquery = 'select ' + #predef + ' from SomeTable';
EXECUTE ( #sqlquery );
One tip: here be dragons. Beware of SQL Injection.

using dynamic IN clause in MSSQL

Why the following SQL does not fetch me anything
DECLARE #Status AS VARCHAR(400)
SET #status = '''Closed'',''OPEN'''
select * from MYTABLE where status in(#status)
While as
select * from MYTABLE where status in('Closed','Open') fetches me rows
You can if you want do some dynamic SQL but I think it is not really competitive..
DECLARE #Status nVARCHAR(400),
#SQL nvarchar(500)
SET #status = '''Closed'''+','+'''OPEN'''
set #SQL = '
select * from [MYTABLE] where status in('+#status +')'
exec sp_executesql #SQL
GO
Your first question checks if the value 'Closed','OPEN' exists in the database. The values is not expanded.
If you use SQL Server 2008 or later you can use Table Valued Parameters to achieve the same thing.