我正在使用此语句将条目从一个表放入另一个表。我需要随机生成的部分对于拉到表A的每条记录都是唯一的,但现在它对所有这些都是相同的。
如何修复此查询,以便@CharacterData变量对于拉入tableA的每条记录都是唯一的?
更新:将随机生成的内容移动到存储过程dbo.RandChars
ALTER PROCEDURE [dbo].[RandChars]
-- Add the parameters for the stored procedure here
(@Length int)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
declare @BinaryData varbinary(max)
, @CharacterData varchar(max)
set @BinaryData=crypt_gen_random(@Length)
set @CharacterData=cast('' as xml).value('xs:base64Binary(sql:variable("@BinaryData"))', 'varchar(max)')
PRINT @CharacterData
END
如何利用此存储过程将唯一的随机字符串放入每行的令牌记录中?
Insert INTO TableA
(TableA.firstname,
TableA.token,
TableA.email,
TableA.emailstatus,
TableA.language,
TableA.remindersent,
TableA.attribute_1,
TableA.attribute_2)
SELECT TableB.[Franchise Location],
[**random string for token**],
TableB.[Franchise Email],
'OK',
'en',
'N',
TableB.[Order Number],
TableB.[Invoice Date]
FROM TableB
WHERE TableB.[Order Date] >= dateadd(DAY, -1, Convert(date, GETDATE()))
答案 0 :(得分:1)
您可以从嵌套选择中的列中选择一个值:
--> set up test data...
create table tableB ( id int )
create table tableA ( id int, rnd varchar(max ) )
go
insert tableB( id ) values( 1 ) ,( 2 ), ( 3 ) --> etc
go
--> do the work...
insert tableA( id, rnd )
select
sub.id,
cast( '' as xml ).value('xs:base64Binary(sql:column( "rx" ) )', 'varchar(max)' )
from
(
select
id,
crypt_gen_random( 4 ) rx
from
tableB
) as sub
go
--> inspect the results...
select * from tableA
go
--> cleanup...
drop table tableA
drop table tableB
...并完全跳过使用程序。
修改强>
因此,使用您的示例,语法更像是:
insert TableA
(
firstname,
token,
email,
emailstatus,
[language],
remindersent,
attribute_1,
attribute_2
)
select
location,
cast( '' as xml ).value('xs:base64Binary(sql:column( "token" ) )', 'varchar(max)' ),
email,
emailstatus,
[language],
remindersent,
attribute_1,
attribute_2
from
(
select
TableB.[FranchiseLocation] location,
crypt_gen_random(30) as token,
TableB.[Franchise Email] email,
'OK' emailstatus,
'en' [language],
'N' remindersent,
TableB.[Order Number] attribute_1,
TableB.[Invoice Date] attribute_2
from
TableB
where
TableB.[Order Date] >= dateadd(DAY, -1, Convert(date, GETDATE()))
) as x
我没有这些表 - 所以这是尝试之前你买的尝试: - )