i tried below code but its not inserting...where i made error.can anyone help me...
DECLARE #str VARCHAR(5)
SELECT #str= Product_Name
FROM tb_new_purchase
WHERE NOT EXISTS (SELECT Product_Name FROM tb_new_product_Name_id where
tb_new_product_Name_id.Product_Name=tb_new_purchase.Product_Name )
DECLARE #key VARCHAR(5), #i int
DECLARE #query VARCHAR(120)
SET #i = 1
WHILE #i > 0
BEGIN
SET #key = (SELECT ABS(Checksum(NewID()) % 467) + 1000)
SET #i = (SELECT count(*) FROM tb_new_product_Name_id WHERE Product_Id = #key)
END
SET #query = 'INSERT INTO tb_new_product_Name_id (Product_Name,Product_Id)
VALUES ('+#str+','+#key+');'
exec(#query)
The semicolon (;) is not part of the SQL syntax (it's a terminator character some tools use) - just remove it from the line you create #query:
SET #query = 'INSERT INTO tb_new_product_Name_id (Product_Name,Product_Id) VALUES ('+#str+','+#key+')'
Related
I am trying to create a unique id based on the given input and the count of the table.
However, I am getting the required output but when using it in program it returns a error stating
SQL Server - An expression of non-boolean type specified in a context
where a condition is expected, near ')'
Here is my code
ALTER PROCEDURE [dbo].[GetpaymentCode]
(
#O_SupplierCode varchar(50) output,
#O_ErrorDesc varchar(100)output
)
AS
BEGIN
declare #Error int
declare #Count char(10)
declare #Qry nvarchar(4000)
declare #QryCondition nvarchar(1000)
DECLARE #Financial_Year VARCHAR(20)
DECLARE #Year VARCHAR(4)
DECLARE #TotalMax VARCHAR(10)
DECLARE #YearMax VARCHAR(10)
DECLARE #TotalCnt INT
DECLARE #YearCnt INT
DECLARE #BillPrefix VARCHAR(5)
DECLARE #BillId VARCHAR(20)
SET #Financial_Year = #O_SupplierCode
SET #BillPrefix = 'P'+SUBSTRING(#Financial_Year,8,2)
PRINT #BillPrefix
TRUNCATE TABLE Tbl_Max
DECLARE #Query NVARCHAR(MAX)
SET #Query = N'WITH T0 AS
(
SELECT MAX(Payment_Id) TotalMax FROM payment_master WHERE Payment_Id
)
, T1 AS
(
SELECT MAX(Payment_Id) YearMax FROM payment_master WHERE Payment_id LIKE ''' + #BillPrefix + '%''
)
INSERT INTO Tbl_Max
SELECT * FROM T0 INNER JOIN T1 ON 1 = 1'
PRINT #Query
EXEC sp_executesql #Query
SELECT #TotalMax = ISNULL(TotalMax,'0'), #YearMax = ISNULL(YearMax,'0') FROM Tbl_Max
IF(#TotalMax != '0')
BEGIN
SET #TotalCnt = CONVERT(INT, SUBSTRING(#TotalMax,6,3)) + 1
END
ELSE
BEGIN
SET #TotalCnt = 1
END
IF(#YearMax != '0')
BEGIN
SET #YearCnt = CONVERT(INT, SUBSTRING(#YearMax,4,2)) + 1
END
ELSE
BEGIN
SET #YearCnt = 1
END
--PRINT #TotalCnt
--PRINT #YearCnt
SET #BillId = #BillPrefix + replace(str(#YearCnt,2),' ','0') + replace(str(#TotalCnt,3),' ','0')
SELECT #BIllId AS BILL_CODE
end
In CTE command in T0 section you have written incomplete where condition.
SELECT MAX(Payment_Id) TotalMax FROM payment_master WHERE Payment_Id =?
Is it possible to print the Dynamic select statement after passing the parameters values.When i print the SELECT #SQL.It is giving only select statement without parameter values.In my below procedure the dynamic select statement not giving correct output after passing the parameters.But when i directly passing the the parameter values into the select statement it is giving correct output.In my below procedure splitting function is working fine.Else part in
if statement is not working properly.
CREATE TYPE TableVariable AS TABLE
(
id int identity(1,1),
field_ids INT,
value VARCHAR(MAX)
)
Alter PROCEDURE Testing
(
#TableVar TableVariable READONLY,
#Catalog_id INT
)
AS
Declare #maxPK INT
Declare #pk INT
Declare #fid INT
Declare #is_List SMALLINT
Declare #val VARCHAR(MAX)
Declare #field_Type VARCHAR(50)
Declare #Where VARCHAR(MAX)
Declare #SQL NVARCHAR(MAX);
Set #pk = 1
BEGIN
BEGIN TRY
SET NOCOUNT ON;
Select #maxPK = count(*) From #TableVar
SELECT #Catalog_id
Set #SQL = 'SELECT DISTINCT v1.entity_id from values v1 inner join listings l ON v1.entity_id = l.entity_id WHERE l.c_id=#Catalog_id'
While #pk <= #maxPK
BEGIN
SELECT #fid= field_ids FROM #TableVar where id=#pk;
SELECT #val= value FROM #TableVar where id=#pk;
SELECT #field_Type=type,#is_List=is_list FROM FIELD WHERE ID=#fid
IF (#is_List = 0)
BEGIN
SET #SQL += ' and exists (select 1 from values v'+convert(varchar(15),#pk+1)+' where v1.entity_id = v'+convert(varchar(15),#pk+1)+'.entity_id and v'+convert(varchar(15),#pk+1)+'.field_id=#fid and(value IN(SELECT val FROM spliting(#val,'',''))))'
SELECT #fid
END
else IF (#is_List = 1 OR #field_Type = 'xy')
BEGIN
SET #SQL += ' and exists (select 1 from values v'+convert(varchar(15),#pk+1)+' where v1.entity_id = v'+convert(varchar(15),#pk+1)+'.entity_id and v'+convert(varchar(15),#pk+1)+'.field_id=#fid and(value in(#val)))'
SELECT #fid
END
Select #pk = #pk + 1
END
EXECUTE SP_EXECUTESQL #SQL, N'#Catalog_id int,#fid int,#val varchar(max)',#Catalog_id=#Catalog_id,#fid=#fid,#val=#val
SELECT #SQL
END TRY
BEGIN CATCH
END CATCH
END
DECLARE #DepartmentTVP AS TableVariable;
insert into #DepartmentTVP values(1780,'Smooth As Silk Deep Moisture Shampoo,Smooth As Silk Deeper Moisture Conditioner')
--insert into #DepartmentTVP values(1780,'Smooth As Silk Deeper Moisture Conditioner')
insert into #DepartmentTVP values(1782,'037-05-1129')
insert into #DepartmentTVP values(2320,'["fairtrade","usda_organic","non_gmo_verified"]')
SELECT * FROM #DepartmentTVP
EXEC Testing #DepartmentTVP,583
Yes right before the statment:
EXECUTE SP_EXECUTESQL #SQL, N'#Catalog_id int,#fid int,#val varchar(max)',#Catalog_id=#Catalog_id,#fid=#fid,#val=#val
type:
print #SQL
How can I retrieve N random records from a set of X records we have in total. For example, if we have a table with 2000 links to different pages on our website how do we retrieve 10 random records?
SELECT TOP 10 *
FROM tableName
ORDER BY NEWID()
NEWID
Try using dynamics SQL like this. Note that this needs more work since some edge cases are not covered such as COUNT() returning 0 or cases where record count is greater than COUNT() and such.
CREATE PROCEDURE dbo.RandomNRecords
(
#recordCount int
)
as
begin
declare #counter int
declare #sqlQuery nvarchar(2000)
SET #sqlQuery = '
CREATE TABLE #TempTable
(
f1 varchar(50),
f2 varchar(50),
f3 int,
id int identity(1,1)
)
INSERT INTO #TempTable
SELECT f1, f2, f3 FROM Table1
SELECT *
FROM #TempTable
WHERE id in ('
SELECT #recordCount = COUNT(*) From Table1
SET #counter = 0
WHILE #counter < #recordCount
BEGIN
SET #counter = #counter + 1
SET #sqlQuery = #sqlQuery + CONVERT(varchar,Round((#recordCount * Rand()), 0)) + ','
END;
SET #sqlQuery = SUBSTRING(#sqlQuery, 1, LEN(sqlQuery) - 1) --remove last comma
SET #sqlQuery = #sqlQuery + ')'
EXEC sp_executesql #sqlQuery
END
declare #numberOfRecordsToGet int = 5
select top (#numberOfRecordsToGet) * from name_of_your_tbl order by newid()
use this in store procedure
declare #N varchar(10)
set #N='10'
exec(' SELECT TOP '+#N+' * FROM tableName ORDER BY NEWID()')
Sometimes we need to debug with our client data and we dont have time to take a complete database backup so we convert manually a sql result to a combination of static 'select UNION select UNION' so we can use their data on the fly...
Example:
select * from items
Results:
Itemcode ItemName Price
Car1 FerrariX 1200.00
Car2 FerrariZ 3000.00
Car3 MustangR 2100.00
And we bring it back to our debuging enviroment like this:
select 'Car1' as Itemcode, 'FerrariX' as Itemname, 1200.00 as 'Price' UNION
select 'Car2', 'FerrariZ', 3000.00 UNION
select 'Car3', 'MustangR', 2100.00
Posible Stored Procedure Solution:
EXEC spQueryAsStaticData #Query = 'select * from items'
How can we do this transformation automatically? Some stored procedure?
i use something like this to print out text using data
DECLARE #i int
DECLARE #employee_id int
Declare #Hash nvarchar(max)
declare #Result nvarchar(max)
Declare #String nvarchar(MAX)
DECLARE #numrows int
DECLARE #employee_table TABLE (
idx smallint Primary Key IDENTITY(1,1)
, [ID] int , [Hash] nvarchar(50), Result nvarchar(50)
)
INSERT #employee_table
SELECT Top 5 * FROM [Hlist].[dbo].[MD5]
set #i =0
set #String = ''
SET #numrows = (SELECT COUNT(*) FROM #employee_table)
IF #numrows > 0
WHILE (#i <= (SELECT MAX(idx) FROM #employee_table))
BEGIN
-- get the next employee primary key
SET #employee_id = (SELECT ID FROM #employee_table WHERE idx = #i)
SET #Hash = (SELECT Hash FROM #employee_table WHERE idx = #i)
SET #Result = (SELECT Result FROM #employee_table WHERE idx = #i)
Set #String = coalesce(#String +'Select '+ convert(varchar,#employee_id) + ', ' +#Hash+ ', '+#Result +' Union ', '')
--
-- do something with this employee
--
-- increment counter for next employee
SET #i = #i + 1
END
Print #String
In the end we solved it developing a little C# app, not as useful as generating it directly from a SQL query but it works...
If someone gives the SQL solution we will grant the answer to him/her
I want get the value from Exec(#sql) and assign to #Rowcount(int)
Here is my query:
'SET #RowCount = (select count(*)
FROM dbo.Comm_Services
WHERE CompanyId = '+cast(#CompanyId as char)+' and '+#condition+')'
On the one hand you could use sp_executesql:
exec sp_executesql N'select #rowcount=count(*) from anytable',
N'#rowcount int output', #rowcount output;
On the other hand you could use a temporary table:
declare #result table ([rowcount] int);
insert into #result ([rowcount])
exec (N'select count(*) from anytable');
declare #rowcount int = (select top (1) [rowcount] from #result);
DECLARE #nReturn int = 0
EXEC #nReturn = Stored Procedure
Was playing with this today... I believe you can also use ##ROWCOUNT, like this:
DECLARE #SQL VARCHAR(50)
DECLARE #Rowcount INT
SET #SQL = 'SELECT 1 UNION SELECT 2'
EXEC(#SQL)
SET #Rowcount = ##ROWCOUNT
SELECT #Rowcount
Then replace the SELECT 1 UNION SELECT 2 with your actual select without the count. I'd suggest just putting 1 in your select, like this:
SELECT 1
FROM dbo.Comm_Services
WHERE....
....
(as opposed to putting SELECT *)
Hope that helps.
that's my procedure
CREATE PROC sp_count
#CompanyId sysname,
#codition sysname
AS
SET NOCOUNT ON
CREATE TABLE #ctr
( NumRows int )
DECLARE #intCount int
, #vcSQL varchar(255)
SELECT #vcSQL = ' INSERT #ctr FROM dbo.Comm_Services
WHERE CompanyId = '+#CompanyId+' and '+#condition+')'
EXEC (#vcSQL)
IF ##ERROR = 0
BEGIN
SELECT #intCount = NumRows
FROM #ctr
DROP TABLE #ctr
RETURN #intCount
END
ELSE
BEGIN
DROP TABLE #ctr
RETURN -1
END
GO
If i understand you correctly, (i probably don't)
'SELECT #RowCount = COUNT(*)
FROM dbo.Comm_Services
WHERE CompanyId = ' + CAST(#CompanyId AS CHAR) + '
AND ' + #condition